如何从集合select字段中获取字符串数组?

How to obtain a string array from a collection select field?

我正在使用 Postgres (0.18.3) 和 Simple Form (3.2.0) 开发 Rails (4.1.8) 应用程序。如何从多select、集合select下拉菜单中获取字符串数组?以下模型和关系与此问题相关:

class FitnessGoal < ActiveRecord::Base
has_and_belongs_to_many :targets
end

class Target < ActiveRecord::Base   
has_and_belongs_to_many :fitness_goals
end

架构中的联接 table:

create_table "fitness_goals_targets", id: false, force: true do |t|
  t.integer "fitness_goal_id"
  t.integer "target_id"
end

健身目标参数:

def fitness_goal params
    params.require(:fitness_goal).permit(:goal_list_id, :timeframe_id, { target_ids: [] }, :activity_id, :notes, :member_id, :trainer_id)

健身目标控制器创建操作:

def create 
  params[:fitness_goal][:target_ids] = params[:fitness_goal][:target_ids].reject{ |target_ids| target_ids.empty? }  
  @fitness_goal = @member.fitness_goals.build(fitness_goal_params)

  if @fitness_goal.save
    flash[:success] = "Fitness goal was successfully created."
    redirect_to member_fitness_goals_path(@member)
  else
    render 'new'
  end
end

Collection_select 新健身目标的表单字段:

<%= f.collection_select :target_ids, Target.order(:outcome), :id, :outcome, {:include_blank => "-- Select one to two --"}, {:multiple => true} %>

相关表单域源代码:

<select id="fitness_goal_target_ids" multiple="multiple" name="fitness_goal[target_ids][]"><option value="">-- Select one to two --</option> 
<option value="1">Lose x pound</option>
<option value="5">Reduce caloric intake by x percent</option>

相关索引查看代码:

<% @fitness_goals.each do |fitness_goal| %>
  <tr id="<%= dom_id(fitness_goal) %>">  
    <td><%= fitness_goal.target_ids.sort.join(', ') %></td>

上面的代码给了我一个选项值数组(例如 [2, 5])。但是,我不想在视图中显示数字选项值,而是想获得 selected 选项文本作为一个字符串数组。换句话说,我希望用户看到的文本输出类似于 ["Lose x pounds"、"Reduce caloric intake by x percent"],而不是视图中的 [2, 5]。我怎样才能实现更多的用户-结果友好吗?谢谢!

将您的索引视图代码修改为:

<% @fitness_goals.each do |fitness_goal| %>
  <tr id="<%= dom_id(fitness_goal) %>
    <td><%= fitness_goal.targets.order(:id).collect(&:outcome).join(', ') %></td>

希望对你有所帮助!