【问题标题】:How to get value of some column of association table in Rails?如何获取 Rails 中关联表的某些列的值?
【发布时间】:2012-08-29 16:18:45
【问题描述】:

如何通过 Record 模型获得产品重量?据我所知,有可能获得特定记录的所有产品,但我无法找到获取特定产品重量的方法。

class User < ActiveRecord::Base
  has_many :eatings
end

class Eating < ActiveRecord::Base
  belongs_to :user
  has_many :records
end

class Record < ActiveRecord::Base
  belongs_to :eating
end

class Product < ActiveRecord::Base
end

class WeightedProduct < ActiveRecord::Base
end

Record 和 Product 模型应该与 WeightedProduct 有什么关系,以便用户能够通过一行 User.first.eatings.first.records.first.products.first.weight 获得某些产品的重量?

【问题讨论】:

    标签: ruby-on-rails ruby ruby-on-rails-3 database-design activerecord


    【解决方案1】:

    看起来你在追求这个:

    class Record < ActiveRecord::Base
      belongs_to :eating
      has_many :weighted_products
    end
    
    class Product < ActiveRecord::Base
      has_many :weighted_products
    end
    
    class WeightedProduct < ActiveRecord::Base
      belongs_to :record
      belongs_to :product
    end
    

    然后User.first.eatings.first.records.first.weighted_products.first.weight

    我认为这应该可行,但尚未测试。

    【讨论】:

      【解决方案2】:

      似乎每个产品都有一个加权产品,那么在这种情况下你应该添加

      class Product < ActiveRecord::Base
       has_one :weighted_product
      end
      
      
      class WeightedProduct < ActiveRecord::Base
       belongs_to :product
      end
      

       class Record < ActiveRecord::Base
        belongs_to :eating
        has_many :products 
       end
      

      【讨论】:

        猜你喜欢
        • 1970-01-01
        • 1970-01-01
        • 2021-02-23
        • 2021-05-18
        • 2013-07-17
        • 2015-10-28
        • 1970-01-01
        • 1970-01-01
        • 2018-11-13
        相关资源
        最近更新 更多