ruby on rails - Updating nested_attribute on a model, doesn't update the has_many through relationship -


i have following model relationship:

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 

permission class has id, name etc.

i using rails 4.2.4 , facing error update method of role model. when update nested attribute permissions_roles, doesn't update has_many :through permissions attribute of model. did verify error in rails console:

> role = role.create(name: 'role', permissions_roles_attributes: [{permission_id: 1}])  # checking permissions role > role.permissions [#<permission:0x007ff3c3963160 id: 1, name: "read">]  # updating nested attributes > role.update(permissions_roles_attributes: [{permission_id: 10}])  # checking nested attributed - return 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">] 

i have manually call reload on model or role.permissions attribute make sure role.permissions updated. there way permissions attribute automatically update whenever update permissions_roles ?

you have forgot specify id of permissionrole model, want update:

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

Comments

Popular posts from this blog

java - Date formats difference between yyyy-MM-dd'T'HH:mm:ss and yyyy-MM-dd'T'HH:mm:ssXXX -

c# - Get rid of xmlns attribute when adding node to existing xml -