botbot
botbot

Reputation: 7359

Rails 3 join table article_categories only allow one category

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!

Upvotes: 0

Views: 256

Answers (2)

Mailo Světel
Mailo Světel

Reputation: 26031

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

rails g migration ArticleHasCategory category:references

Then you specify the article has category in model

belongs_to :category

When you call article.category. It will automatically look for column <relation name>_id which should point to record in <relation name>

Upvotes: 3

badawym
badawym

Reputation: 1509

The Article model should have a belongs_to :category association instead of has_one :category. Also don't forget to add a category_id column to articles table (You can add a migration for that If you haven't already).

Upvotes: 4

Related Questions