Topic: Simple articles in spesific category

Im new to Rails and databases, so im asking:
I have table called Articles which have id (autonumber), text(text) and category(integer).
The other table is the category table which have the names for the categories.
For example category 1 is for Cars and 2 is for Animals.
So how do i create the category table and how do i create the relations for these two tables. And how can i call the specific article that belongs to specific category.? In rails?
I have done these kind of thigs with php and graphical database admin(like phpmySqlAdmin).
But how to do this with Rails and Ruby.

Thanks

Re: Simple articles in spesific category

I had recently created something like this.

My Articles model would have "belongs_to :category"  and my Category model would have "has_many :articles"

Article Model

class Article < ActiveRecord::Base
  belongs_to :category
  ...
end

Category Model
class Category < ActiveRecord::Base
  has_many :articles
end

This is to relate the article entries to a category by haveing a specific ID referencing the respective Category.

So, the articles table would need a "category_id", and not "category".

Articles Migration

class CreateArticles < ActiveRecord::Migration
  def self.up
    create_table :articles do |t|
      t.column :title, :string
      t.column :category_id, :integer
      ...
    end
  end

  def self.down
    drop_table :articles
  end
end


Category Migration
class CreateCategories < ActiveRecord::Migration
  def self.up
    create_table :categories do |t|
      t.column :name, :string
    end
  end

  def self.down
    drop_table :categories
  end
end


This is my simple approach.  Hopefully this helps you?

Re: Simple articles in spesific category

This is just what i was looking for.

Thank you...

Re: Simple articles in spesific category

Heh.. And how do I make a scaffold to enter the article and choose the category(which i have filled erlier) from drop menu?

Re: Simple articles in spesific category

You can do this with collection_select.

# in article form
<%= collection_select :article, :category_id, Category.find(:all), :id, :name %>

Railscasts - Free Ruby on Rails Screencasts

Re: Simple articles in spesific category

What is the difference between select and collection_select?

=====================
Sam G.

Re: Simple articles in spesific category

With "select" you specify the options with a two dimentional array. With "collection_select" you specify the options with an array of objects (models) and you provide the two methods you want to call on those objects (id and name).

Railscasts - Free Ruby on Rails Screencasts