【发布时间】:2018-03-12 22:47:59
【问题描述】:
在 Rails 中,我们有 has_many 功能:
class Product < ApplicationRecord
has_many :product_sales
has_many :states, through: :product_sales
end
有什么方法可以给这些has_manys 之一指定一个自定义名称吗?
例如:我不想使用@product.states从Product访问states,而是使用@product.states_where_it_is_sold访问它。
【问题讨论】:
-
是的,肯定有办法做到这一点。我相信您想查看guide 的第 4.3.2.9 节。而且,也许只是
@product.states_where_sold,但这是个人喜好问题。 -
@jvillian,感谢您的回复:D。我试过这样:
has_many :states, through: :product_sales, source: :states_where_it_is_sold,但它不起作用=/ -
改用
source: :state。source应指ProductSale上的belongs_to :state字段。 -
没关系,我只是使用
has_many :states_where_it_is_sold, through: :product_sales, source: :state完成的。请您写一个答案,以便我将其设置为正确吗?
标签: ruby-on-rails database has-many-through has-many