Saturday, February 12, 2011

How do I access a nested model from view?

I have a drop down like this on my page:

<p>
     <%= f.label :episode_id %><br />
     <%= f.collection_select(:episode_id, @episodes, :id, :show) %>
</p>

An episode has an id and belongs_to to a show which has a name. In the dropdown, I'd like to display the show name. :show.name doesn't work to display the name. How do I do this?

  • One way to do this would be to create a method in your Episode class called show_name like so:

    def show_name
      show.name
    end
    

    The last symbol you are passing into collection_select is the name of the method that you want to call to get the option text.

  • I don't know if this would work, but did you try episode.show.name?

    Owen : Doesn't work. :-( That was the first thing I tried.
    From salt.racer
  • You could use #select instead of #collection_select. You need to do a bit more work to construct the value/text pairs, but it's not too bad.

    f.select(:episode, :id, @episodes.map{|e| [e.show.name, e.id]})
    
    From madlep

0 comments:

Post a Comment