سؤال

Please read the following four lines carefully:

first_post = Discourse.create(title: 'I am the first post')
# => #<Discourse id: 56, user_id: nil, title: "I am the first post", body: nil, deleted: nil, delete_date: nil, created_at: "2014-04-07 12:34:53", updated_at: "2014-04-07 12:34:53", forum_id: nil> 
first_reply = first_post.replies.create(title: 'I am the first reply to the first post')
# => #<Discourse id: 57, user_id: nil, title: "I am the first reply to the first post", body: nil, deleted: nil, delete_date: nil, created_at: "2014-04-07 12:35:29", updated_at: "2014-04-07 12:35:29", forum_id: nil> 
second_reply = first_post.replies.create(title: 'I am the second reply to the first post')
# => #<Discourse id: 58, user_id: nil, title: "I am the second reply to the first post", body: nil, deleted: nil, delete_date: nil, created_at: "2014-04-07 12:35:41", updated_at: "2014-04-07 12:35:41", forum_id: nil> 
first_reply_reply = second_reply.retorts.create(title: 'I am the first retort to the second reply to the first retort')
# => #<Discourse id: 59, user_id: nil, title: "I am the first retort to the second reply to the fi...", body: nil, deleted: nil, delete_date: nil, created_at: "2014-04-07 12:36:53", updated_at: "2014-04-07 12:36:53", forum_id: nil> 
  • I regard first_post to have a "depth" of 0 because it isn't a reply to anything.

  • I regard first_reply to have a "depth" of 1 because it is a reply to first_post (0 + 1 = 1)

  • I regard second_reply to have a "depth" of 1 because it is a reply to first_post (0 + 1 = 1)

  • I regard first_reply_reply to have a "depth" of 2 because it is a reply to second_reply that is in-turn a reply to first_post (1 + 1 = 2)

And so on. A reply to first_reply_reply would be 3. (1 + 2 = 3)

To determine the depth of each association I could easily add a column depth to my table and simply create a model method with a before_save hook to iterate the depth, however I wonder if the depth can already be worked out in rails. Maybe an active record method?

هل كانت مفيدة؟

المحلول

You should be able to write:

class Discourse < AR::Base

  ...

  def depth
    <parent_association> ? <parent_association>.depth + 1 || 1
  end
end

Where <parent_association> is your association to access to record to which this record is a response to. However this will require a number of database calls, so your approach with before_save hook is much better. You can also hava a look at ancestry gem, which very well handles tree-like associations (including depths).

مرخصة بموجب: CC-BY-SA مع الإسناد
لا تنتمي إلى StackOverflow
scroll top