Welcome to OGeek Q&A Community for programmer and developer-Open, Learning and Share
Welcome To Ask or Share your Answers For Others

Categories

0 votes
243 views
in Technique[技术] by (71.8m points)

ruby on rails - Rails4 : How to assign a nested resource id to another resource

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 ?

See Question&Answers more detail:os

与恶龙缠斗过久,自身亦成为恶龙;凝视深渊过久,深渊将回以凝视…
Welcome To Ask or Share your Answers For Others

1 Reply

0 votes
by (71.8m points)

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


与恶龙缠斗过久,自身亦成为恶龙;凝视深渊过久,深渊将回以凝视…
OGeek|极客中国-欢迎来到极客的世界,一个免费开放的程序员编程交流平台!开放,进步,分享!让技术改变生活,让极客改变未来! Welcome to OGeek Q&A Community for programmer and developer-Open, Learning and Share
Click Here to Ask a Question

...