Let’s say I have a catalog with hotels. Each hotel belongs to a
category (4-star, 5-star etc.) This is it’s official category.However,
there is also a category that users assign and a category that
“independent reviewers” assign. So I have this:
hotels {
id,
category_id,
reviewer_category,
user_category
}
categories {
id,
name
}
class Hotel < ActiveRecord::Base
belongs_to :hotel_class # this is fine and ok
can I also something like this, however?
belongs_to :hotel_class,
:foreign_key => ‘reviewer_category’
belongs_to :hotel_class,
:foreign_key => ‘user_category’
end
I would really really really hate to do something like
HotelCategory.find(:first, :conditions => …) for every hotel
request. I want ORM 
What’s the approach to such a situation?
Thank you
Dmitrii D. wrote:
Let’s say I have a catalog with hotels. Each hotel belongs to a
category (4-star, 5-star etc.) This is it’s official category.However,
there is also a category that users assign and a category that
“independent reviewers” assign. So I have this:
hotels {
id,
category_id,
reviewer_category,
user_category
}
categories {
id,
name
}
class Hotel < ActiveRecord::Base
belongs_to :hotel_class # this is fine and ok
can I also something like this, however?
belongs_to :hotel_class,
:foreign_key => ‘reviewer_category’
belongs_to :hotel_class,
:foreign_key => ‘user_category’
end
You can set up a separate association for each such foreign key, and
specify the name of the key as part of the association. You should
always use a name ending in _id for such foreign keys.
class Hotel < ActiveRecord::Base
belongs_to :category
belongs_to :reviewer_category,
:class_name=> ‘Category’, :foreign_key => ‘reviewer_category_id’
belongs_to :user_category,
:class_name=> ‘Category’, :foreign_key => ‘user_category_id’
end
–
Josh S.
http://blog.hasmanythrough.com
end
Thank you! I totally overlooked the :class_name thing.
Dmitrii D. wrote:
Thank you! I totally overlooked the :class_name thing.
Newbie clarification question:
If a model has multiple belongs_to references, you ahve to specify a
class name and a foreign key?
I understand the foreign key, but what’s the logic behind specifying the
class name? What does that do?
–
Austin
Austin G. wrote:
If a model has multiple belongs_to references, you ahve to specify a
class name and a foreign key?
I understand the foreign key, but what’s the logic behind specifying the
class name? What does that do?
Rails infers the class of the related object from the name of the field.
So belongs_to :user_category will by default assume it is a UserCategory
model, which is wrong. You override that default by setting the
class_name option. Unfortunately setting the class_name also sets the
foreign_key name, so you have to specify that explicitly as well. I
believe in Rails 2.0 that will be changed so that it’s more DRY.
–
Josh S.
http://blog.hasmanythrough.com