0

レコード モデルを使用して製品の重量を取得するにはどうすればよいですか? 私が知っているように、特定の記録のすべての製品を取得することは可能ですが、特定の製品の重量を取得する方法を見つけることができません.

ここに画像の説明を入力

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

ユーザーが User.first.eatings.first.records.first.products.first.weight の 1 行で特定の製品の重量を取得できるようにするには、WeightedProduct を使用して Record モデルと Product モデルを作成する必要があります。

4

2 に答える 2

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

私はそれがうまくいくはずだと思いますが、テストしていません。

于 2012-08-29T16:36:39.897 に答える
0

各製品には 1 つの加重製品があるようです。その場合は、追加する必要があります。

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
于 2012-08-29T16:47:15.547 に答える