views:

34

answers:

2

I have model represent association rule (Body => Head)

def Item
has_many :heads
has_many :bodies
...
end

def Rule
has_many :heads
has_many :bodies
...
end

def Body
belongs_to :item
belongs_to :rule
...
end

def Head
belongs_to :item
belongs_to :rule
...
end

I want to find rule that have body's item matched items specified and want to access its head via Rule but I can't do like

def Rule
has_many :heads
has_many :bodies
has_many :item, :through => :heads
has_many :item, :through => :bodies
...
end

What should I change and do to accomplish this ?

Thanks,

A: 
def Rule
  has_many :heads
  has_many :bodies
  has_many :head_items, :through => :heads
  has_many :body_items, :through => :bodies
  ...
end

You need to different has_many associations for each.

james2m
I should have head_items and body_items models as inheritance of items ?
art
A: 

Finally I come up with this solution

class Rule
  has_many :heads
  has_many :bodies
  ...
end
class Body
  belongs_to :rule
  has_many :items, :as => :rulable
end
class Head
  belongs_to :rule
  has_many :items, :as => :rulable
end
class Item
  belongs_to :rulable, :polymorphic => true`
end

Don't sure if this is a good solution, but this is what I use for now.

art