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?
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
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.
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 %>
来源:https://stackoverflow.com/questions/22519540/rails-4-concatenate-fields-in-collection-select