Find By ID


#1

Hi folks,

Newbie with ruby on rails but very excited by the features provided by
the framework :wink:

Suppose I’ve got a table ‘Company’ and a table ‘Category’ Company
belongs to a category but I will retrieve the Catagory in the Company
list?
It seems that I don’t have the basic ruby wau of thinking to get this
easily.

Can someone help?

Many thanks in advance

Stef


#2

Stephane Gauthier wrote:

Hi folks,

Newbie with ruby on rails but very excited by the features provided by
the framework :wink:

Suppose I’ve got a table ‘Company’ and a table ‘Category’ Company
belongs to a category but I will retrieve the Catagory in the Company
list?
It seems that I don’t have the basic ruby wau of thinking to get this
easily.

Can someone help?

Many thanks in advance

Stef

Ok, found it.

company.category.name … so simple!


#3

hi,

Just to note, your tables should be a plural version of the models:
companies
categories

Your companies table will have ‘category_id’ that references the ‘id’
field in the categories table.

You models will then be set up to reflect this relationship:

class Company < ActiveRecord::Base
belongs_to :category
end

class Category < ActiveRecord::Base
has_many :companies
end

You’ll then be able to retrive company and find it’s assigned category:

get company (assuming you have a company with id=1)

company = Company.find(1)

get category name

category_name = company.category.name

For a great introduction to all this, the Agile book
(http://www.pragmaticprogrammer.com/titles/rails/index.html) is highly
recommended.

Hope that helps,

Steve


#4

Stephen B. wrote:

hi,

Just to note, your tables should be a plural version of the models:
companies
categories

Your companies table will have ‘category_id’ that references the ‘id’
field in the categories table.

You models will then be set up to reflect this relationship:

class Company < ActiveRecord::Base
belongs_to :category
end

class Category < ActiveRecord::Base
has_many :companies
end

You’ll then be able to retrive company and find it’s assigned category:

get company (assuming you have a company with id=1)

company = Company.find(1)

get category name

category_name = company.category.name

For a great introduction to all this, the Agile book
(http://www.pragmaticprogrammer.com/titles/rails/index.html) is highly
recommended.

Hope that helps,

Steve

Yes, I already got this.

thanks