如何在Rails中自定义间接has_many关联的名称?

时间:2018-03-12 22:48:00

标签: ruby-on-rails database has-many-through has-many

在Rails中,我们有has_many功能:

class Product < ApplicationRecord
  has_many :product_sales
  has_many :states, through: :product_sales
end

有什么办法可以为其中一个has_many提供自定义名称吗?

例如:我不想使用statesProduct访问@product.states,而是希望使用@product.states_where_it_is_sold访问它。

1 个答案:

答案 0 :(得分:3)

是的,有办法。做:

class Product < ApplicationRecord
  has_many :product_sales
  has_many :states_where_sold, through: :product_sales, source: :state
end