如何在 Rails 中自定义间接 has_many 关联的名称?
How do I customize the name of an indirect has_many association in Rails?
在Rails中,我们有has_many
特征:
class Product < ApplicationRecord
has_many :product_sales
has_many :states, through: :product_sales
end
有什么方法可以为这些 has_many
之一指定自定义名称吗?
例如:我不想使用 @product.states
从 Product
访问 states
,而是想使用 @product.states_where_it_is_sold
.
访问它
是的,有办法。做:
class Product < ApplicationRecord
has_many :product_sales
has_many :states_where_sold, through: :product_sales, source: :state
end
在Rails中,我们有has_many
特征:
class Product < ApplicationRecord
has_many :product_sales
has_many :states, through: :product_sales
end
有什么方法可以为这些 has_many
之一指定自定义名称吗?
例如:我不想使用 @product.states
从 Product
访问 states
,而是想使用 @product.states_where_it_is_sold
.
是的,有办法。做:
class Product < ApplicationRecord
has_many :product_sales
has_many :states_where_sold, through: :product_sales, source: :state
end