On Tue, May 11, 2010 at 5:00 AM, Colin Law <clan...@googlemail.com> wrote: > On 10 May 2010 21:56, sso <strongsilent...@gmail.com> 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| %> >> <tr> >> <td><%=h record.band.name %></td> > > 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 ... <td><%=h record.artist %></td> 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: http://github.com/rubyredrick Twitter: @RickDeNatale WWR: http://www.workingwithrails.com/person/9021-rick-denatale LinkedIn: http://www.linkedin.com/in/rickdenatale -- You received this message because you are subscribed to the Google Groups "Ruby on Rails: Talk" group. To post to this group, send email to rubyonrails-t...@googlegroups.com. To unsubscribe from this group, send email to rubyonrails-talk+unsubscr...@googlegroups.com. For more options, visit this group at http://groups.google.com/group/rubyonrails-talk?hl=en.