0

I have these two activerecord models:

Milestone
  has_many :nodes

Node
  belongs_to :milestone

Milestones can have multiple nodes because it's possible to create aliases. I then need a way to find the master node.

I tried two options but none of them work completely:

Option 1: add an association :node :

 belongs_to :node, conditions: {is_alias: true}

Looks obvious to me but doesn't work at all. When I do @milestone.node, the result is "nil"

Option 2: create a node method:

  def node
     Node.where(milestone_id: self.id, is_alias: false)
  end

This works halfway:

@milestone.node => returns the right node

@milestone.node.milestone => returns an error: undefined method `milestone' for #

I need a "clean" way to be able to find the master parent milestone information.

4

1 回答 1

1

您需要 Node 模型中的一些范围和类方法

scope :aliases, where(is_alias: true)
scope :masters, where(is_alias: false)

def self.master
  masters.first
end

所以你可以这样使用

@milestone.nodes.master  # => master node
@milestone.nodes.aliases # => aliases
于 2012-04-06T13:13:43.630 回答