I’m setting up a music catalogue to learn my way around RoR. In
index.html.erb I would like to show the band name instead of the id.
What is the proper way to do this?
records.rb
class Record < ActiveRecord::Base
belongs_to :band;
end
bands.rb
class Band < ActiveRecord::Base
has_many :records
end
I’m setting up a music catalogue to learn my way around RoR. In
index.html.erb I would like to show the band name instead of the id.
What is the proper way to do this?
records.rb
That should be record.rb, not records
class Record < ActiveRecord::Base
belongs_to :band;
end
bands.rb
Again, should be singular
class Band < ActiveRecord::Base
has_many :records
end
views/records/index.html.erb
…
<% @records.each do |record| %>
<%=h record.band.name %>
That should work, assuming you change the filenames above. Watch out
for the case where no band has been allocated, however, ie record.band
is nil
That should work, assuming you change the filenames above. Watch out
for the case where no band has been allocated, however, ie record.band
is nil
Which is one reason that I’d recommend not having the view reach
through one model to get to the attributes of another, a violation of
the “law” of demeter (which I personally call the “strong suggestion”
of demeter.
So I’d do something like:
in the view
…
<%=h record.artist %>
and in the record model
class Record < ActiveRecord::Base
belongs_to band
def artist
if band
band.name
else
“Anonymous”
end
end
end
This decouples the view from the DB representation, and will make
changes down the road like changing the database schema to allow
multiple artist compilations to be represented, when you will change
the belongs_to and has_many relations in Record and Band to either
has_and_belongs_to_many or has_many :through associations.