来自其他模型的复杂关联

时间:2016-02-03 14:04:57

标签: postgresql ruby-on-rails-4 activerecord

我有四个模特

class RestaurantSpecialPrice < ActiveRecord::Base
  belongs_to :restaurant
  belongs_to :stock
end

class Stock < ActiveRecord::Base
  has_many :stock_prices, dependent: :destroy
  has_many :restaurant_special_prices, dependent: :destroy
  has_many :restaurants, through: :stock_prices
end

class Restaurant < ActiveRecord::Base

  has_many :stock_prices, dependent: :destroy
  has_many :restaurant_special_prices, dependent: :destroy
  has_many :stocks, through: :stock_prices
  has_many :stocks_with_special_prices, through: :restaurant_special_prices, source: :stock
end

class StockPrice < ActiveRecord::Base
  belongs_to :restaurant
  belongs_to :stock
end

我想创建餐厅特价和股票价格之间的关联,以便我可以获得股票的原始价格如何将它们两者联系起来最好的方式。我知道我可以得到像这样的记录

special = RestaurantSpecialPrice.last
StockPrice.where(restaurant: special.restaurant, stock: special.restaurant)

我也可以通过连接和包括这样做,但我希望通过适当的关联。

1 个答案:

答案 0 :(得分:0)

  

我希望RestaurantSpecialPrice.first的股票价格与关联

您已经有这样的关联:

class Restaurant < ActiveRecord::Base
  has_many :stock_prices, dependent: :destroy
end

使用它:

Restaurant.first.stock_prices