2009-09-08 103 views
0

有没有一种方法可以直接引用(直接使用rails,而不诉诸大量的自定义SQL)嵌套在多态关系后面的关系?在下面的例子中,是否有一种方法可以在User中定义一个引用LayerTwo的has_many关系?has_many:通过,嵌套多态关系

我想要做的(用户)

has_many :layer_twos, :through => layer_ones 

但这种方法并没有考虑到该帐户先前指定的has_many关系,通过多态的关系。有什么建议么?这可能不是通过现有的铁路公约,但我认为我会把问题推迟给那些更聪明的人。

class CreateOwners < ActiveRecord::Migration 
    def self.up 
    create_table :users do |t| 
     t.timestamps 
    end 
    create_table :owners do |t| 
     t.timestamps 
     t.references :owned, :polymorphic => :true 
     t.references :user 
    end  
    create_table :layer_ones do |t| 
    end 
    create_table :layer_twos do |t| 
     t.references :layer_one 
    end 
    end 
end 


class Owner < ActiveRecord::Base 
    belongs_to :user 
    belongs_to :owned, :polymorphic => true 
end 

class User < ActiveRecord::Base 
    has_many :owners 
    has_many :layer_ones, :through => :owners, :source => :owned, :source_type => 'LayerOne' 
end 

class LayerOne < ActiveRecord::Base 
    has_many :owners, :as => :owned 
    has_many :layer_twos 
end 

class LayerTwo < ActiveRecord::Base 
    belongs_to :LayerOne 
end 

回答

1

据我所知,ActiveRecord不支持:通过a:through关系。你可以使用一些技巧和黑客来解决这个问题,比如创建一个将关系重新映射成更直接的VIEW,这可以简化你的ActiveRecord模型,但会牺牲数据库的复杂性。

多态性协会是特别ornery。

+0

感谢只想做个验证与某人其他。 – 2009-09-08 16:43:57

1

我不知道它支持通过多态asociations筑巢,但它可能是值得检查出nested_has_many_through插件,它从自述:

...能够定义 的has_many :through关系,这 通过其他has_many:through 关系,可能通过 任意深层次结构。此 允许协会跨越任何数量的表 要构造,而不必诉诸于find_by_sql(其 不是合适的解决方案,如果需要通过 :include 做急切装载以及) 。

+0

是的,这将起作用。你必须小心,不要太深入地嵌套你的应用程序。我写了一篇博文,分步展示:http://kconrails.com/2010/01/28/nesting-has_many-through-relationships-in-ruby-on-rails/ – 2010-10-23 03:14:36

0

试试这个(Rails 3中):

class LayerOne < ActiveRecord::Base 
    class << self 
    def layer_twos 
     LayerTwo.where(:layer_one_id => all.map(&:id)) 
    end 
    end 
end