can I do a "named_scope" for this scenario???


Is it possible to do a named_scope (or “has_many, :through…”) for this scenario:

  • Class: Node

  • Class: Relationships

  • node_id

  • dependant_node_id

QUESTION: So how can I get a “has_many” or “named_scope” happening within the Node class such that it would:

(a) pass back ALL relationships, including both those relationships for which the node instance is either referenced by (i) node_id, or (ii) dependant_node_id. This might be called something like “all_relationships”

(b) pass back ALL nodes at the other end of the relationships identified by (a), but not including in the returned array of nodes the instance node in question. This might be called something “all_direct_related_nodes”.

PS. To further clarify my question note that:

class Node < ActiveRecord::Base

has_many :relationships_as_child, :class_name => ‘Relationship’, :foreign_key => :dependant_node_id
has_many :relationships_as_parent, :class_name => ‘Relationship’, :foreign_key => :node_id

def all_relations
Relationship.find(:all, :conditions => [“node_id = ? OR dependant_node_id = ?”,,])

I can get the first two “has_many” working, but I can’t work out how to effectively combine these two into one “has_many”. I can create a “all_relations” method however that does provide the full flexibility of a “has_many” or a “named_scope” version (which I’m after) as I can’t then do further things like:

Node.find(1).all_relations.find(1) # fails

So in other words I want the output of the “all_relations” function, but in the form of a “has_many” or a “named_scope”.

Any help welcomed :slight_smile:

You could try:

named_scope :all_relations_for, lambda { |o| { :conditions =>
["node_id = :o_id OR dependant_node_id = :o_id", { :o_id => }] } }

That will let you do:

Node.all_relations_for(Node.find(1)) etc.

Not quite as snazzy as what you're looking for, but close...

--Matt Jones

thanks, but this doesn’t bring back Relationships, it brings back Nodes…does a named_scope always bring back instances of the class it’s specified in it does it?

I really want a “named_scope”, or “has_many” version of the method “all_relations” in my original email below…any more ideas anyone?


I think my solution was aiming more for the all_direct_related_models
part; sorry for the confusion.

You should be able to do the other half with a named scope on
Relationship, basically with the same scope:

class Relationship < ...
  named_scope :all_relations_for, lambda { |o| { :conditions =>
["node_id = :o_id OR dependant_node_id = :o_id", { :o_id => }] } }

Then drop a method into your Node model:

class Node < ...
  def all_relations

--Matt Jones