ruby-on-rails - rails 4 has_many :through not saving associations

标签 ruby-on-rails has-many-through has-many strong-parameters

我有 2 个具有多对多关联的模型,如下所示:

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

和关系:

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

应该执行保存的 remarks_controller 操作:

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

和形式:

<%= 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 %>

Remarks_controller:

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

用户和备注都已经存在,我需要一个用于创建关联的表单,最好使用复选框。

在控制台中,关联已保存。但是我花了最后一天的时间试图让它在浏览器中工作。我已经阅读了所有我能找到的关于这个问题的资料,但我现在很困惑。

谁能告诉我实际的表单应该是什么样子,以及是否需要在 Controller 中添加任何其他内容?

最佳答案

你的表单没有任何问题,但可以简化为以下内容

<%= 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 %>

然后在您的 Controller 中,您可以从 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

关于ruby-on-rails - rails 4 has_many :through not saving associations,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/19923897/

相关文章:

ruby-on-rails - Rails 协会不会触发 Postgres 查询并返回 Nil

sorting - Emberjs 高级排序 hasMany 关联作为计算属性

ruby-on-rails - Rails 安装 Ubuntu 12.04 期间出错

mysql - Homebrew - 无法安装Sphinx

ruby-on-rails - 通过 ID 数组的关联创建多个 has_many

ruby-on-rails - 如何在 Rails 中同时通过对象保存多个 has_many?

ruby-on-rails - 如何控制ActiveRecord在构建查询时是否使用$1,$2..占位符?

ruby-on-rails - 为 AJAX 请求设计验证用户

rspec - 如何在 FactoryBot 中使用 has_many 关联设置工厂

ruby-on-rails - 在 ruby​​ on rails 中使用 has_many 和使用数组有什么区别? (MongoDB)