I am wondering how to build a join table articles_categories, but one where there can only be one category per article. I know the typical way to do categories is to allow multiple categories for each article with has_and_belongs_to_many, but I’d like only allow one category per article. I have already set up my articles_categories join table with the has_and_belongs_to_many associations. I followed an example from Apress Beginning Rails 3, that also recommended to set the articles_categories table :id => false. Will I also have to update the table to have an id? Thanks!
So far I have updated my articles model to has_one :category and the category model to has_many :articles, but I get an error while testing in irb:
a = Article.first
a.category
The error is:
Category Load (0.7ms) SELECT "categories".* FROM "categories" WHERE "categories"."article_id" = 1500 LIMIT 1
PG::Error: ERROR: column categories.article_id does not exist
LINE 1: SELECT "categories".* FROM "categories" WHERE "categories"...
Can somebody tell me how to better set this up? Thanks!
If you want each article has only one category you should not use cross table. Simply use references in migration — http://guides.rubyonrails.org/migrations.html#highlighter_472212
Then you specify the article has category in model
When you call
article.category. It will automatically look for column<relation name>_idwhich should point to record in<relation name>