我想知道到什么程度,我可以在滑轨使用关联。考虑到以下内容:

class User < ActiveRecord::Base
    has_one :provider
    has_many :businesses, :through => :provider
end

class Provider < ActiveRecord::Base
    has_many :businesses
    has_many :bids, :through => :businesses
    belongs_to :user
end

class Business < ActiveRecord::Base
    has_many :bids
    belongs_to :provider
end

class Bid < ActiveRecord::Base
    belongs_to :business
end

我能够设置这些漂亮的快捷键像User.businessesProvider.bids但如何做这样的事情User.bids?是否有可能的关联关联,可以这么说?

有帮助吗?

解决方案

这是完全有可能的,但需要一些额外的工作。与href="http://github.com/ianwhite/nested_has_many_through" rel="noreferrer"> nested_has_many插件您可以获取属于与刚@user.bids用户所有投标下面的模型定义

class User < ActiveRecord::Base
    has_one :provider
    has_many :businesses, :through => :provider
    has_many :bids, :through => :businesses
end

class Provider < ActiveRecord::Base
    has_many :businesses
    has_many :bids, :through => :businesses
    belongs_to :user
end

class Business < ActiveRecord::Base
    has_many :bids
    belongs_to :provider
end

class Bid < ActiveRecord::Base
    belongs_to :business
end

然而获得从出价用户将需要更多的工作。

其他提示

如果你只是想获取记录,为什么不使用使用 #delegate ?它工作得很好,至少在你所描述的情况。

class User < ActiveRecord::Base
    has_one :provider
    delegate :bids, :to => :provider
end

class Provider < ActiveRecord::Base
    has_many :businesses
    has_many :bids, :through => :businesses
    belongs_to :user
end

class Business < ActiveRecord::Base
    has_many :bids
    belongs_to :provider
end

class Bid < ActiveRecord::Base
    belongs_to :business
end

虽然我不那么谦虚,认为你应该只是链的方法,因为它更简单,而且你不再实现性能提升,除非你有一些疯狂的自定义SQL去为tadman说。

虽然这是有一个非常有用的东西,你不能HAS_MANY:通过的has_many:通过关系。这是加入发动机的限制。

接法可以是使用一个聪明的子选择,或在这种情况下的子子选择,或有意地非规范化的表足以减少该深度。

例如,由于业务的提供者的上下文中所定义,它按理说,任何出价元件也被分配,间接向提供商。建设投标和提供者之间的直接联系将使查询竞价直接方便。

有什么能阻止你做这样的事情据我所知:

class User < ActiveRecord::Base
    has_one :provider
    has_many :businesses, :through => :provider

    def bids
        user_bids = []
        businesses.each |business| do
            user_bids += business.bids
        end
        user_bids
    end
end

class Provider < ActiveRecord::Base
    has_many :businesses
    has_many :bids, :through => :businesses
    belongs_to :user
end

class Business < ActiveRecord::Base
    has_many :bids
    belongs_to :provider
end

class Bid < ActiveRecord::Base
    belongs_to :business
end

然后调用@ user.bids应该产生期望的结果,也可以缓存出价,如果你想要做其他花哨的东西。

许可以下: CC-BY-SA归因
不隶属于 StackOverflow
scroll top