使用collection_select在HABTM关系中创建多个记录-Rails [英] Creating multiple records in a HABTM relationship using a collection_select - Rails
问题描述
我在锻炼和小组之间有一个has_and_belongs_to_many
关系.
I have a has_and_belongs_to_many
relationship between workouts and groups.
我正在使用分组中的collection_select
来向组中添加锻炼.
I have a collection_select
in groups that I'm using to add workouts to groups.
问题是我只能更改HABTM表中的一条记录,因此我只能添加一条记录,然后编辑该记录.如何添加其他记录?
The problem is that I can only change the one record in the HABTM table, so I can only add one record, then edit that record. How do I add additional records?
有什么想法吗?
这是一些代码:
show.html.erb:
<%= form_for(@group) do |f| %>
<%= f.collection_select 'workout_ids', Workout.all, :id, :name, { :include_blank => ""} %>
<%= f.submit %>
<% end %>
.
class Workout < ActiveRecord::Base
attr_accessible :name, :exercises_attributes, :workout_exercises_attributes, :group_ids
has_and_belongs_to_many :groups
.
class Group < ActiveRecord::Base
attr_accessible :cycle_id, :name, :next_group_id, :previous_group_id, :workout_ids
has_and_belongs_to_many :workouts
推荐答案
因此,答案是使用以下命令在控制器中编辑更新操作:
So the answer to this is to edit the update action in the controller with this:
workout_id = params[:group].delete(:workout_ids)
# Adding a workout
if workout_id
workout = Workout.find(workout_id)
@group.workouts << workout
end
上面的代码创建了一个局部变量workout_id
,该局部变量从:group
中获取参数:group
和:workout_id
..delete
方法删除了第二个参数,用于在更改名称时更新实际组.例如,组.
The above code creates a local variable workout_id
that takes the parameters :group
and :workout_id
from within :group
the .delete
method removes the second parameter for updating the actual group when you change the name of the group, for example.
然后,我们只需将新的锻炼方式推送到@ group.workouts上,就可以在每次从集合选择中向组中添加新锻炼方式时在联接表中创建新记录.
Then we simply push a new workout onto @group.workouts, creating a new record in the join table every time we add a new workout to the group from the collection select.
这篇关于使用collection_select在HABTM关系中创建多个记录-Rails的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!