开发者

How do I perform advanced logic when a specific field is updated in Rails?

Say I have a three models that look (basically) like this:

class User < ActiveRecord::Base
  has_many :projects
  has_many :deliverables
end

class Project < ActiveRecord::Base
  belongs_to :user
 开发者_如何学C has_many :deliverables
end

class Deliverable < ActiveRecord::Base
  belongs_to :user
  belongs_to :project
end

Now, say I want the following to happen: when a project is transferred from one user to another, all associated deliverables will be transferred along with it. So something like:

project = Project.find(some_criteria)

deliverables = project.deliverables

project.user_id = new_user_id

deliverables.each do |d|
  d.user_id = new_user_id
end

Is there some way to automate what I just described? I could always of course just put that into a method (like transfer_user), but I would prefer for it to happen automatically whenever user_id is set to a new value.


You probably still want to implement the transfer_user method, but add a callback in your project model by doing:

class Project < ActiveRecord::Base
  after_save :transfer_user, :if => "user_id_changed?"
end
0

上一篇:

下一篇:

精彩评论

暂无评论...
验证码 换一张
取 消

最新问答

问答排行榜