Getting data from an ancestor (I think)

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

views/records/index.html.erb


<% @records.each do |record| %>

<%=h record.band.name %> <%=h record.title %> <%=h record.description %> ...

On 10 May 2010 21:56, sso [email protected] wrote:

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

Colin

On Tue, May 11, 2010 at 5:00 AM, Colin L. [email protected]
wrote:

belongs_to :band;

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

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.


Rick DeNatale

Blog: http://talklikeaduck.denhaven2.com/
Github: rubyredrick (Rick DeNatale) · GitHub
Twitter: @RickDeNatale
WWR: http://www.workingwithrails.com/person/9021-rick-denatale
LinkedIn: http://www.linkedin.com/in/rickdenatale