Associations

Hi, I’ve got a problem with two models, connected via belongs_to and
has_many associations. Lets say they are Article, and Category. In the
Article the key is article_id and foreign key column is category_id, in
the Category is key category_id (so keys are not just id). How can I
solve this (categories.id does not exist Fparse_func.c L1036
Runknown_attribute: SELECT * FROM categories WHERE (categories.id = 1)
LIMIT 1)? I need to specify that the key in category is not id but
category_id…

Thanks

fafa wrote:

Hi, I’ve got a problem with two models, connected via belongs_to and
has_many associations. Lets say they are Article, and Category. In the
Article the key is article_id and foreign key column is category_id, in
the Category is key category_id (so keys are not just id). How can I
solve this (categories.id does not exist Fparse_func.c L1036
Runknown_attribute: SELECT * FROM categories WHERE (categories.id = 1)
LIMIT 1)? I need to specify that the key in category is not id but
category_id…

class Article < ActiveRecord::Base
set_primary_key “article_id”
belongs_to :category, :foreign_key => “category_id”
end

And likewise in Category.


Josh S.
http://blog.hasmanythrough.com

If all your tables follow the _id format you can configure this
at
the app level with a change in environment.rb. Add this at the bottom of
the
file:

ActiveRecord::Base.primary_key_prefix_type = :table_name_with_underscore

If some tables have “id” and others are _id (granted that’s a
messy
way to design a schema) you can do this:

class Category < ActiveRecord::Base
self.primary_key = “category_id”
end

Henry
http://www.henrywagner.org/