Creating multiple records in a HABTM relationship using a collection_select - Rails

a 夏天 提交于 2019-12-08 05:47:42

问题


I have a has_and_belongs_to_many relationship between workouts and groups.

I have a collection_select in groups that I'm using to add workouts to groups.

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?

Any ideas?

Here is some code:

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

回答1:


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

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.

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.



来源:https://stackoverflow.com/questions/16107343/creating-multiple-records-in-a-habtm-relationship-using-a-collection-select-ra

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