簡體   English   中英

rails has_many:通過has_many:through

[英]rails has_many :through has_many :through

我想知道我可以在多大程度上使用Rails中的關聯。 考慮以下因素:

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那樣做什么呢? 是否可以關聯一個協會,可以這么說?

這是完全可能的,但需要一些額外的工作。 以下模型定義與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:through關系來實現。 這是聯接引擎的限制。

替代方案要么使用聰明的子選擇,要么在這種情況下使用子子選擇,或者有意地對表進行非規范化以足以減少連接深度。

例如,由於業務是在提供商的上下文中定義的,因此任何Bid元素也間接地分配給提供商。 在Bid和Provider之間建立直接關聯可以直接輕松查詢出價。

沒有什么可以阻止你做這樣的事情:

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 4.0協議,如果您需要轉載,請注明本站網址或者原文地址。任何問題請咨詢:yoyou2525@163.com.

 
粵ICP備18138465號  © 2020-2024 STACKOOM.COM