rails 4 has_many :through not saving associations

我只是一个虾纸丫 提交于 2019-12-06 03:29:13

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