1

这有点棘手,所以如果您需要更多信息,请不要犹豫!

我有两个模型,Store它们Consumer通过两种方式链接:

1/StoreConsumer继承自同一个模型Profile,因为它们共享许多属性(姓名、位置、电子邮件、网页……)。这是 Rails AR 代码:

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

class Store << Profile
end

class Consumer << Profile
end

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

2/ 除了 STI,Store并且Consumer通过多对多关系链接:

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

  • 消费者是许多商店的客户

因为我需要这个链接(商店 - 消费者)的更多属性,所以我必须创建一个额外的模型来链接它们: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)。那么,如何定位Client具有 store_id 和 client_id 的正确行?

知道怎么做吗?提前致谢。

4

1 回答 1

3

I think you want to do is something like this. Also, I agree with Daniel Wright's comment.

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

But if you'd like to make it work with what you have you could do something like:

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
于 2012-10-03T14:50:47.433 回答