在模型上更新nested_attribute,不会更新has_many通过关系

时间:2015-09-21 10:59:06

标签: ruby-on-rails ruby-on-rails-4

我有以下模特关系:

class Role < ActiveRecord::Base
  has_many :permissions_roles, inverse_of: :role, dependent: :destroy
  has_many :permissions, through: :permissions_roles
  accepts_nested_attributes_for :permissions_roles, allow_destroy: true
end

class PermissionsRole < ActiveRecord::Base
  belongs_to :permission
  belongs_to :role
end

权限类有idname等。

我正在使用Rails 4.2.4并面临着角色模型更新方法的错误。当我更新嵌套属性permissions_roles时,它不会更新模型的has_many:through permissions属性。这就是我在rails控制台中验证错误的方法:

> role = Role.create(name: 'role', permissions_roles_attributes: [{permission_id: 1}])

# Checking permissions for the role
> role.permissions
[#<Permission:0x007ff3c3963160
id: 1,
name: "read">]

# Updating the nested attributes
> role.update(permissions_roles_attributes: [{permission_id: 10}])

# Checking nested attributed - Return as expected
> role.permissions_roles
=> [#<PermissionsRole:0x007ff3bbade740 id: 78, permission_id: 1, role_id: 11>, #<PermissionsRole:0x007ff3bc8fdee8 id: 79, permission_id: 10, role_id: 11>]

# Checking has_many through relationship. Stale :(
> role.permissions
=> [#<Permission:0x007ff3be1d29f0
id: 1,
name: "read">]

我必须在模型或reload属性上手动调用role.permissions以确保更新role.permissions。有permissions属性是否有任何方法可以在我更新permissions_roles时自动更新?

1 个答案:

答案 0 :(得分:0)

您忘记指定要更新的PermissionRole模型的ID:

role.update(permissions_roles_attributes: [{ id: 78, permission_id: 10}])