Add parent query methods #97

Closed
wants to merge 1 commit into
from

Conversation

Projects
None yet
2 participants

sj26 commented Aug 1, 2012

While adding ancestry to some STI classes I found myself wanting to add a validation to restrict non-leaf nodes:

class Leaf < ActiveRecord::Base
  has_ancestry

  validate :parent_is_leaf_group, if: :parent?

  def parent_is_leaf_group
    errors.add :parent, "is not leaf group" unless parent.is_a? LeafGroup
  end
end

class LeafGroup < Leaf
  # Things Leaf can't have...
end

Sadly, my friend the query attribute method (parent?) wasn't available—so I added it. It adds greater semantic value than if: :parent_id in situations like this, while being more efficient than if: :parent.

Tests were added also, but one test on master was already failing.

xymbol commented Oct 2, 2012

@sj26 I would probably rename the method to avoid confusion between having and being a parent node.

sj26 commented Oct 3, 2012

It's meant to reflect the attribute query methods which already exist for most attributes and associations on activemodels, but I'm open to has_parent? and is_parent? or something.

StefanH closed this in 8650a52 May 7, 2013

sj26 commented May 7, 2013

Very nice, thanks!

Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment