Confused on setting up a has_many relationship
I have been playing with setting up different relationships for a few hours now and I am not sure how to do a has_many relationship with what I am using. Not sure if it is just naming conflicts or my just not understanding.
Here is my database table开发者_开发技巧s:
show_names (table name):
id
show_id
name
shows (table name):
id
length
synopsis
number_of_episodes
status
So each show has many possible names. So I want to setup a has_many relationship so I can call something like:
Show.all.shownames[0].name
That would give me the first name.
Here are my code samples for my models, and its where I think I am messing up.
class ShowName < ActiveRecord::Base
has_many :shows
end
and
class Show < ActiveRecord::Base
belongs_to :shownames
end
Using ShowName.all works to get data and Show.all works too.
So I have 2 main questions about this.
1) Am I just misnaming something or putting it in the wrong place? 2) How do I access the show names? I know in other using has_one i just use the name of the entity does it work the same with has_many
Any help is appreciated.
You flipped the belongs_to and has_many and needed an extra underscore. Try this:
class ShowName < ActiveRecord::Base
belongs_to :show
end
and
class Show < ActiveRecord::Base
has_many :show_names
end
and now...
show = Show.first
show.show_names => ["First name for first show", "Second name for second show"]
精彩评论