我有以下模特关系:
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
权限类有id
,name
等。
我正在使用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
时自动更新?
答案 0 :(得分:0)
您忘记指定要更新的PermissionRole
模型的ID:
role.update(permissions_roles_attributes: [{ id: 78, permission_id: 10}])