What is the right association between these two models?
I am building a blog and I am a Rails newbie. The doubt is about how to stablish the association between these too models: Posts and Languages.
There will be just two languages, and each post will only (belong_to/has) one language. I was thinking that the right thing would be:
class Post < ActiveRecord::Base
belongs_to :language
end
class Language < ActiveRecord::Base
has_many :posts
end
Is it the right approach? Cause sounds more natural to think开发者_开发知识库 that a post has_one language and a language belongs_to_many posts but this kind of association isn't possible in rails, am i wrong?.
Sorry for such an newbie question. Thanks in advance.
You are correct. If you have two models in a many-to-one relationship, your only option is to put has_many
on the "one" model and belongs_to
on the "many" model. So, in your case, you do indeed want the snippet you provided.
Remember that this means your posts
table will carry a language_id
column (which feels right), and that your code will refer to post.language
and language.posts
.
精彩评论