rails 4 has_many :through not saving associations

旧街凉风 提交于 2019-12-07 16:10:20

问题


I have 2 models with many to many association as follows:

class User < ActiveRecord::Base
    has_many :remark_users, :dependent => :destroy
    has_many :designated_remarks, :through => :remark_users, :source => :remark
end

class Remark < ActiveRecord::Base
     has_many :remark_users, :dependent => :destroy
    has_many :users, :through => :remark_users

    accepts_nested_attributes_for :users
end

And the relationship:

class RemarkUser < ActiveRecord::Base
    belongs_to :remark
    belongs_to :user
end

The remarks_controller action that should do the save:

# PATCH Save users
def save_users
    @remark = Remark.find(params[:id])
    @remark.users.build(params[:remark_user_ids])
    @remark.save
end

And the form:

<%= form_for @remark, :url => salveaza_responsabili_remark_path(@remark) do |f| %>
    <% @users.each do |user| %>
        <%= check_box_tag 'remark[remark_user_ids][]', user.id, @remark.users.include?(user) %>
        <%= user.name %>
    <% end %>
    <%= hidden_field_tag 'remark[remark_user_ids][]', '' %>
<% end %>

Te remarks_controller:

params.require(:remark).permit(:description, :suggestion, :origin_details,  process_type_id, :origin_id, :remark_user_ids)

Both the User and the Remark already exists, I need a form just for creating the associations, preferably using check boxes.

In Console, the association is saved. But I spend last day trying to make it work in the browser. I have read all what I could find on this matter, and I am very confused right now.

Can someone point me on what the actual form would have to look like, and if there is need to add anything else in the controller?


回答1:


There's nothing wrong with your form but it can be simplified to the following

<%= form_for @remark, :url => salveaza_responsabili_remark_path(@remark) do |f| %>
  <% @users.each do |user| %>
    <%= check_box_tag 'user_ids[]', user.id, @remark.users.include?(user) %>
    <%= user.name %>
  <% end %>
<% end %>

Then in your controller, you can expect an array from params[:user_ids]

def save_users
  @remark = Remark.find(params[:id])

  # This is where you need to think about things.  If the checkbox in the form
  # contains all the users for a remark, the following code should work.
  #
  # @remark.user_ids = params[:user_ids]
  # @remark.save
  # 
  # otherwise, you have to loop through each user_id
  params[:user_ids].each do |user_id|
    @remark.remark_users.create!(user_id: user_id)
  end
end


来源:https://stackoverflow.com/questions/19923897/rails-4-has-many-through-not-saving-associations

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