简体   繁体   English

simple_form关联未正确更新

[英]simple_form association not updating correctly

In Rails 4.0.2, I have the following models/relationships: 在Rails 4.0.2中,我具有以下模型/关系:

class User < ActiveRecord::Base
  has_many :client_account_assignments
  has_many :clients, -> { uniq }, through: :client_account_assignments
  ...
end

class Client < ActiveRecord::Base
  has_many :client_account_assignments
  has_many :users, -> { uniq }, through: :client_account_assignments
  ...
end

In the edit.html.haml view for users, I have the following form: 在用户的edit.html.haml视图中,我具有以下形式:

= simple_form_for @user do |f|
  = f.association :clients, as: :select, collection: Client.all, value_method: :id, label_method: :name, include_blank: false, input_html: {data: {placeholder: "Choose..."}}

Adding clients to a user works as expected. 将客户端添加到用户可以正常工作。 However, deselecting one or more clients does not work correctly. 但是,取消选择一个或多个客户端无法正常工作。 For example: 例如:

  1. @user.id => 1 @user.id => 1

  2. @user.clients.map(&:id) => [70, 74, 76, 71, 72, 73, 75] @user.clients.map(&:id) => [70,74,76,71,72,73,75]

  3. Navigate to users/1/edit 导航到users/1/edit

  4. Deselect all clients except the client with id of 76. 取消选择除ID为76的客户端以外的所有客户端。

  5. Set breakpoint in UsersController#update . UsersController#update设置断点。

  6. Click "save". 点击“保存”。

  7. params[:user][:client_ids] => ["", "76", "", "70", "71", "72", "73", "74", "75", "76"] params[:user][:client_ids] => [“”,“ 76”,“”,“ 70”,“ 71”,“ 72”,“ 73”,“ 74”,“ 75”,“ 76”]

Why are all the previously-selected, now-unselected client ids being passed in the params? 为什么所有先前选择的,现在未选择的客户端ID都会在参数中传递?

Another example: 另一个例子:

  1. @user.id => 1 @user.id => 1

  2. @user.clients.map(&:id) => [70] @user.clients.map(&:id) => [70]

  3. Navigate to users/1/edit 导航到users/1/edit

  4. Deselect all clients, except for the clients with ids of 71 and 72. 取消选择所有客户端,但ID为71和72的客户端除外。

  5. Click "save". 点击“保存”。

  6. params[:user][:client_ids] => ["", "71", "72", "", "70"] params[:user][:client_ids] => [“”,“ 71”,“ 72”,“”,“ 70”]

Again, why is the old client id (ie, 70) still appearing in the params? 同样,为什么旧​​的客户端ID(即70)仍出现在参数中?

原来这是一个简单的答案:我不小心在视图上多次渲染了客户输入,因此保留了旧值。

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM