使用`assign_attributes`可以通过以下方式立即保存has_many:

Rem*_*emo 5 activerecord ruby-on-rails activemodel ruby-on-rails-5

据我所知,assign_attributes(不像update_attributes)不应保存记录或就此保存任何记录。

所以当我发现提供_ids一个has_many through:关系。

考虑以下示例:

class GroupUser < ApplicationRecord
  belongs_to :group
  belongs_to :user
end

class Group < ApplicationRecord
  has_many :group_users
  has_many :users, through: :group_users
end

class User < ApplicationRecord
  has_many :group_users
  has_many :groups, through: :group_users

  validates :username, presence: true
end
Run Code Online (Sandbox Code Playgroud)

因此,我们的用户和用户组之间是一对一的关系。

Group.create # Create group with ID 1
Group.create # Create group with ID 2

u = User.create(username: 'Johny')

# The following line inserts two `GroupUser` join objects, despite the fact 
# that we have called `assign_attributes` instead of `update_attributes` 
# and, equally disturbing, the user object is not even valid as we've 
# supplied an empty `username` attribute.
u.assign_attributes(username: '', group_ids: [1, 26])
Run Code Online (Sandbox Code Playgroud)

评论者要求的日志:

irb(main):013:0> u.assign_attributes(username: '', group_ids: [1, 2])
  Group Load (0.2ms)  SELECT "groups".* FROM "groups" WHERE "groups"."id" IN (1, 2)
  Group Load (0.1ms)  SELECT "groups".* FROM "groups" INNER JOIN "group_users" ON "groups"."id" = "group_users"."group_id" WHERE "group_users"."user_id" = ?  [["user_id", 1]]
   (0.0ms)  begin transaction
  SQL (0.3ms)  INSERT INTO "group_users" ("group_id", "user_id", "created_at", "updated_at") VALUES (?, ?, ?, ?)  [["group_id", 1], ["user_id", 1], ["created_at", "2017-06-29 08:15:11.691941"], ["updated_at", "2017-06-29 08:15:11.691941"]]
  SQL (0.1ms)  INSERT INTO "group_users" ("group_id", "user_id", "created_at", "updated_at") VALUES (?, ?, ?, ?)  [["group_id", 2], ["user_id", 1], ["created_at", "2017-06-29 08:15:11.693984"], ["updated_at", "2017-06-29 08:15:11.693984"]]
   (2.5ms)  commit transaction
=> nil
Run Code Online (Sandbox Code Playgroud)

我敢说,update_attributes_ids结构主要用于处理Web表单-在这种情况下,该表单会更新用户本身及其组关联。因此,我认为可以肯定地说这里的一般假设是全部或全部,而不是部分节省。

我在某种程度上使用错误吗?

Dav*_*bia 2

@gokul-m 建议在https://github.com/rails/rails/issues/17368上阅读有关该问题的信息。其中一条评论指出了一种临时解决方法:https://gist.github.com/sudoremo/4204e399e547ff7e3afdd0d89a5aaf3e