开发者

Using after_save to update all belongs_to records

I'm building a project management application in Ruby on Rails (3.0). I am trying to figure out how to update all the tasks of a project on update of a project column. Here is the situation.

I am listing all the projects, as expected, in /projects/index.html.erb. I'm using a sortable list (from Ryan Bates tutorial) to update the project.position field as the user sorts the list.

Whe开发者_如何学JAVAn the project list gets sorted the project.position column gets updated on each sort, I also want to update the task.project_position column of all the tasks that belong_to that project. So task.project_position = project.position.

I am guessing that this is done through an after_save in the project model but I could be totally wrong.


Don't store the value multiple times - that's redundant and unnecessary in all but a few esoteric cases.

In Ruby/Rails you can delegate from the task to the project for the position method like this (in your Task model):

delegate :position, :to => :project, :prefix => true, :allow_nil => true

With that in place, you now have task.project_position which will return the value of project.position via the association between the two, without duplication of that data element across all tasks in the project.

All this assumes that task belongs_to :project (and probably, project has_many :tasks).

more detailed explanation.

If you feel you really must go the de-normalized route for some reason, then yes, after_save would be the place to do it.

0

上一篇:

下一篇:

精彩评论

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

最新问答

问答排行榜