Rails4 : How to assign a nested resource id to ano

2019-09-14 03:13发布

Model:

order & material
order has_many materials
material belongs_to order

material & user
material has_may users
user belongs_to material

Assume I create a material with id = 20 , order_id = 1

In materials_controller update action, I want to assign material id to specific users.In materials_controller update action I did it like this

    if @material.update_attributes(material_params)
      if @material.ready == true
        @users = User.where("is_manager = 't'")
        @users.each do |user|
          user.material_id = @material.id
        end
      end
   end

But attribute material_id in user did not get changed after the action. Anybody could tell me what cause the failure to pass material id to user ?

2条回答
Deceive 欺骗
2楼-- · 2019-09-14 03:40

You also need to do user.save after you change user.material_id.

      user.material_id = @material.id
      user.save #Saves the changes

That changed the attribute of user object, but the change has not been persisted yet. It's now a stale object which has some attributes changed. To persist those attributes, user.save is required.

Or you can use update_attribute like below:

if @material.update_attributes(material_params)
  if @material.ready
    @users = User.where("is_manager = 't'")
    @users.each do |user|
      user.update_attribute(:material_id, @material.id)
    end
  end

end

查看更多
Ridiculous、
3楼-- · 2019-09-14 03:47

You might want to have a look at update_all.

update_all updates all records in one SQL statement instead of loading all records into memory and sending N update queries to the database. This makes update_all much faster than iterating over multiple users.

if @material.ready
  User.where(is_manager: 't').update_all(material_id: @material.id) 
end

Often it is an issue, that update_all doesn't validate the records before updating. But in this case this behavior is actually preferred.

查看更多
登录 后发表回答