Pregunta

Hello I am attempting to add categories to my posts and I am a little confused on how to set up the relation for this one.

Should a post have_many categories or should a category have_many posts?

Ideally what I want to do is have one table that I seed with particular categories which in my head is a table with id's and a simple alias column for each category name.

When making a post I want a select with all the categories in place and just assign a value. So if I picked value = 1 it should probably place the "1" into the categories_id column which gets referenced and I know that 1 = Some category.

Maybe?

¿Fue útil?

Solución

In your case,it should be categories has_many posts and post belongs to category

Class Category < ActiveRecord::Base

has_many :posts, dependent: :destroy 

end

Class Post < ActiveRecord::Base

belongs_to :category

end

By giving this,you should be having a category_id(Foreign key) in your posts table.

So when you are creating a post,you can able to select categories through a collection_select or select.

Hope it helps!

Licenciado bajo: CC-BY-SA con atribución
No afiliado a StackOverflow
scroll top