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

时间:2015-12-22 23:16:32

标签: ruby-on-rails arrays postgresql simple-form

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

class FitnessGoal < ActiveRecord::Base
has_and_belongs_to_many :targets
end

class Target < ActiveRecord::Base   
has_and_belongs_to_many :fitness_goals
end

架构中的连接表:

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]。但是,我不想在视图中显示数字选项值,而是希望将所选选项文本作为字符串数组获取。单词,而不是视图中的[2,5],我希望用户看到文本输出,如[&#34;丢失x磅&#34;,&#34;减少热量摄入量x%&#34;]。我实现了这个更加用户友好的结果?谢谢!

1 个答案:

答案 0 :(得分:1)

将索引视图代码修改为:

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

希望,这有帮助!