gpt4 book ai didi

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

转载 作者:行者123 更新时间:2023-11-29 13:25:38 24 4
gpt4 key购买 nike

我正在使用 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)

健身目标 Controller 创建操作:

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])。但是,我不想在 View 中显示数字选项值,而是希望将选定的选项文本作为字符串数组获取。在其他情况下换句话说,而不是 [2, 5] 在 View 中,我希望用户看到像 ["Lose x pounds", "Reduce caloric intake by x percent"] 这样的文本输出。我怎样才能实现这个更用户友好的结果?谢谢你!

最佳答案

将您的索引 View 代码修改为:

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

希望对您有所帮助!

关于ruby-on-rails - 如何从集合选择字段中获取字符串数组?,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/34426044/

24 4 0
Copyright 2021 - 2024 cfsdn All Rights Reserved 蜀ICP备2022000587号
广告合作:1813099741@qq.com 6ren.com