# Associations

**URL:** <https://www.ruby-forum.com/t/associations/88864>\
**Category:** Rails\
**Created:** [March 15, 2007, 3:37am UTC](https://www.ruby-forum.com/t/associations/88864 "2007-03-15T03:37:13Z")\
**Posts on this page:** 3\
**Page:** 1

<div class="post-metadata">

**Author:** ![fafa](https://www.ruby-forum.com/letter_avatar_proxy/v4/letter/f/8e7dd6/32.png) [@fafa](https://www.ruby-forum.com/u/fafa)\
**Post date:** [March 15, 2007, 3:37am UTC](https://www.ruby-forum.com/t/associations/88864/1 "2007-03-15T03:37:13Z")

</div>

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

---

<div class="post-metadata">

**Author:** ![fafa](https://www.ruby-forum.com/letter_avatar_proxy/v4/letter/f/8e7dd6/32.png) [@fafa](https://www.ruby-forum.com/u/fafa)\
**Post date:** [March 15, 2007, 5:11am UTC](https://www.ruby-forum.com/t/associations/88864/2 "2007-03-15T05:11:24Z")

</div>

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](http://blog.hasmanythrough.com)

---

<div class="post-metadata">

**Author:** ![fafa](https://www.ruby-forum.com/letter_avatar_proxy/v4/letter/f/8e7dd6/32.png) [@fafa](https://www.ruby-forum.com/u/fafa)\
**Post date:** [March 15, 2007, 6:57pm UTC](https://www.ruby-forum.com/t/associations/88864/3 "2007-03-15T18:57:06Z")

</div>

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/](http://www.henrywagner.org/)
