在Rails中,我们有has_many
功能:
class Product < ApplicationRecord
has_many :product_sales
has_many :states, through: :product_sales
end
有什么办法可以为其中一个has_many
提供自定义名称吗?
例如:我不想使用states
从Product
访问@product.states
,而是希望使用@product.states_where_it_is_sold
访问它。
答案 0 :(得分:3)
是的,有办法。做:
class Product < ApplicationRecord
has_many :product_sales
has_many :states_where_sold, through: :product_sales, source: :state
end