gpt4 book ai didi

ruby-on-rails - rails has_many :through has_many :through

转载 作者:数据小太阳 更新时间:2023-10-29 06:44:13 26 4
gpt4 key购买 nike

我想知道我可以在多大程度上使用 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 plugin 结合使用您只需使用 @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

然而,通过出价获得用户需要更多的工作。

关于ruby-on-rails - rails has_many :through has_many :through,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/2051927/

26 4 0
Copyright 2021 - 2024 cfsdn All Rights Reserved 蜀ICP备2022000587号
广告合作:1813099741@qq.com 6ren.com