开发者

Have a nested parent model pointing to the first child model

My models are like this: a discussion has_many posts (nested resource).

I want to add a starter_post_id column to the discussions table, and have it record the 'thread starter post id'. The discussion is created along with the post in the nested form, and that when the logic should be called, because other posts to that discussion will be replies not starter posts.

I am not sure what I need to do after the add_column db migration.

  1. Do I need a belongs_to :post in my Discussion model?
  2. What's the order of creation 开发者_开发技巧for these nested objects. e.g. parent's creation ends before child's starts? or will the parent constructor call the child constructor?
  3. Which model should the starter post assignment logic go to? This is related to Q2 since both objects needs to be initiated, but preferably before the DB call.


I would use the created_at field from you post model to determine the starter_post of a discussion. No need for any columns.

Add something like this in your discussion model

def starter_post
  self.posts.order("created_at ASC").first()
end

If you use this in you discussion.rb :

has_many :posts , :order => "created_at ASC"

you can then simply use :

def starter_post
  self.posts.first()
end


I tried before_save and it won't work because at that point in time the discussion has no way to get hold of the starter post object. I was pointed out to use after_create instead.

def after_create
    self.starter_post_id = self.posts.first.id
    self.save!
end

This will cause one extra sql query, but it is better than doing it at the post model.

I used belongs_to so I can use discussion.start_post_id, but I guess it is optional.

0

上一篇:

下一篇:

精彩评论

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

最新问答

问答排行榜