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

标签 ruby-on-rails ruby orm associations rails-activerecord

我想知道我可以在多大程度上使用 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/

相关文章:

javascript - Rails CoffeeScript - 如何包含 JavaScript 文件(正在开发中)?

Ruby/Selenium 问题识别列表中显示的项目

C# - Kerosene ORM - 找不到默认引擎和连接字符串

ruby-on-rails - rails 4 : polymorphic set base class type instead of inherited

mysql - Rails 4.2.2 - mysql2 安装错误

css - 将复选框与标签内联

java - Hibernate JPA一对一保存子类实体

mysql - 想要在数组中查询并获取传递给查询的 id 的结果

ruby - 使用 Nokogiri::HTML 和 Ruby 进行网页抓取 - 如何将输出输出到数组中?

sql - Sequelize findAll 多对多条件