开发者

Problem find joined table in rails

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_m开发者_开发技巧any :item, :through => :bodies
...
end

What should I change and do to accomplish this ?

Thanks,


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.


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.

0

上一篇:

下一篇:

精彩评论

暂无评论...
验证码 换一张
取 消

最新问答

问答排行榜