Associations and attributes

Hello!

I’m having an issue with attributes within associations!

Here it is the thing I don’t arrive to understand : I have 3 classes :
Bands, Answers and Questions.

Answers belongs_to Bands and Questions.
Questions has_many Answers
Bands belongs_to Questions and has_many Answers.

When a Band is created, there some Answers to give. The results are
correctly displayed with the exact correspondant id (I mean “band.id”).
What I would like to do is to show the band’s name on Answer’s index. To
do this, I’ve tried different solutions like:
<% @answers.each do |answer| %>
<%= answer.band %>
or also
<%= answer.band_name %>
and also
<%= answer.band.band_name %>

I’ve tried to do a local variable which is
a = answer.band_id
Band.find_by_id(a).band_name

but it then says that there’s no method called band_name , even if the
association is made and functioning. Once that is done, shouldn’t a
class have all the attributes of the other???
By the way, in the console it works everything, and for instance I can
do something like
a = Answer.find(26)
a.band_name = Band.find(25).band_name
a.save
=> true
a.band_name
=> “Yo”

but if I do the same on the browser => index.html.erb , it doesn’t work.

So, where am I mistaking? Should I inverse the associations and set
Bands as belonged from Answers?

Hi.

I believe that your association is not correct. Could you post your
models? Try belongs_to :band instead of bands. It a 1:n not an n:m.

Cheers
Alex

Yes, it was correctly written, I was just mistaken here!

I was thinking, should I inverse the relationships?

Hi

belongs_to :bands won’t work
in answers table you should have band_id field and in the Answer model
belongs_to :band
(this will build the 1 of the relation)

in bands table you need an id field and in the Band model you need
has_many :answers
(this will be the n in the relation)

now you have a 1:n relation that enables you to do:

band.answers…
and
answer.band…

if band has a band_name then

answer.band.band_name will work

if you want answers to have many bands and bands to have my answers you
need the n:m relation. In that case you need to add a table called
answers_bands with columns band_id and answer_id (the table name need’s
to be answers_bands NOT bands_answers!)

in the models you specify the relation using
Answer model:
has_and_belongs_to_many :bands
Band model:
has_and_belongs_to_many :answers

then you will be able to do
band.answers…
and
answer.bands…

Hope that helps

Alex