如何获取Rails中某些关联表列的值?

时间:2012-08-29 16:18:45

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

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

enter image description here

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

记录和产品型号与WeightedProduct有什么关系,因此用户可以通过一行获取某些产品的重量User.first.eatings.first.records.first.products.first.weight?

2 个答案:

答案 0 :(得分: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

我认为这应该有效,但尚未经过测试。

答案 1 :(得分:0)

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

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