3

I'm working on learning Rails 4 via several tutorials, and building a demo app.

I have a table called players that links to a team table. The team has many players, a player has only one team. So I'm using a collection_select tag to pull the team data into the player form.

It looks like this:

<%= collection_select :player, :team_id, Team.find(:all), :id, :name, options ={:prompt => "Select a team"} %>

This works fine-- but I'd like to have the format look like "Team Name: Team City"-- I can't figure out how to concatenate the :name and :city values in the tag however. Is this possible?

user101289
  • 9,888
  • 15
  • 81
  • 148

3 Answers3

15

Create a method in your Team model like the following one

  def name_with_city
    "#{name}: #{city}"
  end

Then use it as below

<%= collection_select :player, :team_id, Team.find(:all), :id, :name_with_city, {:prompt => "Select a team"} %>

Find out more about collection_select in the documentation

Rafa Paez
  • 4,820
  • 18
  • 35
0

You can format the collection to your liking as:

<%= collection_select :player, 
    :team_id, 
    Team.find(:all).collect { |t| [ t.id, "#{t.name}: #{t.city}" ] },
    :first, 
    :last,  
    { prompt: "Select a team" } %>

The :id and :name parameters have been replaced with first and last signifying the value_method to be first and text_method to be last elements of each array.

vee
  • 38,255
  • 7
  • 74
  • 78
0

If your form is looking up values based on parameters and you need those, the model method is not very convenient. Assuming your controller has a @searched_record method, you can do something like

<% @base_params = @searched_record.one_value << "=>" << @searched_record.second_value << "; " << (l(@searched_record.starts, :format => :long)) << ", " << @searched_record.other_value.description %>
      <%= f.text_area :content, :rows => 5, value: @base_params %>
Jerome
  • 5,583
  • 3
  • 33
  • 76