2012-10-03 138 views
1

这有点棘手,所以如果您需要更多信息,请不要犹豫!导轨:链接两个继承相同型号的模型

我有两个型号,StoreConsumer由两种方式联系:

1/Store,并从同一个模型ProfileConsumer inherite,因为他们有许多共同的属性(名称,地址,电子邮件,网页, ...)。这里是Rails AR代码:

class Profile << ActiveRecord::Base 
    # Attributes and validation rules go here. 
end 

class Store << Profile 
end 

class Consumer << Profile 
end 

这是众所周知的单表继承(STI)。

2 /除了STI,StoreConsumer由许多与许多关系:

  • 商店有许多客户(很多消费者)

  • 消费者是客户许多商店

因为我需要这个链接(商店 - 消费者)更多的属性,我必须创建一个额外的模型,将链接他们:Client

这里是我最后的AR模型:

class Profile << ActiveRecord::Base 
    # Attributes and validation rules go here. 
end 

class Store << Profile 
    has_many :clients 
end 

class Consumer << Profile 
    has_many :clients 
end 

class Client << ActiveRecord::Base 
    belongs_to :store 
    belongs_to :consumer 
end 

问题

使用STI不会产生STORE_ID和consumer_id ......我们只有PROFILE_ID(因为一个真正的表Profile)。那么,我该如何定位正确的具有store_id和client_id的Client行?

任何想法如何做到这一点?提前致谢。

+0

什么你所描述的是不是性病。 STI是当两种模型是某种事物的类型时:一辆车和一辆SUV是车辆的类型;猫和狗是动物的类型。在你的情况下,商店和消费者不是配置文件的类型。你有什么(最好)是'has_one'关系:Store has_one Profile;消费者拥有一个配置文件。您可能正在寻找一个维护痛苦的世界,试图将STI压在您的域模型上。 –

+0

你知道了吗? –

+0

@TimothyHunkele:我现在只是在尝试它(似乎我们连接起来了!!)。在阅读丹尼尔的解释之后,我看到STI是否真的有必要。保持联系... – htaidirt

回答

3

我想你想要做的就是这样。另外,我同意Daniel Wright的评论。

class Profile << ActiveRecord::Base 
    belongs_to :store 
    belongs_to :consumer 
end 

class Store << ActiveRecord::Base 
    has_one :profile 
    has_many :clients 
    has_many :consumers, :through => :clients 
end 

class Consumer << ActiveRecord::Base 
    has_one :profile 
    has_many :clients 
    has_many :stores, :through => :clients 
end 

class Client << ActiveRecord::Base 
    belongs_to :store 
    belongs_to :consumer 
end 

但是,如果你想使你有你可以做类似的工作是什么:

class Profile << ActiveRecord::Base 

end 

class Store << Profile 
    has_many :clients, :foreign_key => 'store_id' 
    has_many :consumers, :through => :clients 
end 

class Consumer << Profile 
    has_many :clients, :foreign_key => 'consumer_id' 
    has_many :stores, :through => :clients 
end 

class Client << ActiveRecord::Base 
    belongs_to :store 
    belongs_to :consumer 
end 
+0

非常感谢Timithy的帮助和详细的代码!它工作非常好。 – htaidirt