ruby on rails - Eager load associations in nested set model -


i'm using nested set represent nested comments (1 discussion has many comments, comments can replied to) , (if possible) eager load answers comments.

at moment load root nodes , iterate on them, if have descendants render them. however, if there lot of root nodes answers, triggers lot of db requests.

a comment has these columns: rgt, lft, parent_id

i tried create relationship this:

class comment < activerecord::base   has_many :answers, -> (node) { where("lft > ? , rgt < ?", node.lft, node.rgt) }, class_name: "comment", foreign_key: :parent_id end 

this fetches answers comment when called on comment instance. however, if try eager_load (discussion.comments.includes(:answers)) blows since node nil.

is possible eager load this?

i think, i've found solution. if see right, data model looks this:

discussion ---------- ...  comment ---------- discussion_id:int parent_id:int lft:int rgt:int 

then ar model classes be:

class discussion < activerecord::base   has_many :comments end  class comment < activerecord::base   belongs_to :discussion end 

to eager load discussion (id == 1) tree of comments , answers use:

d = discussion.includes(:comments).find(1) 

this gives collection of comments given discussion in memory (d.comments).

now can manipulate collection answers particular comment without additional db queries. add discussion class:

def comment_roots   self.comments.select {|c| c.parent_id.nil? } end 

and comment class:

  def answers     self.discussion.comments.select {|c| c.parent_id = self.id }   end    def answers_tree     self.discussion.comments.select {|c| self.lft < c.lft && c.rgt <   self.rgt }   end 

example:

d.comment_roots.first.answers 

Comments

Popular posts from this blog

Payment information shows nothing in one page checkout page magento -

tcpdump - How to check if server received packet (acknowledged) -