rails 4 — concatenate fields in collection_select

痞子三分冷 提交于 2019-12-06 06:57:56

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 %>
易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!