【问题标题】:How do I customize the name of an indirect has_many association in Rails?如何自定义 Rails 中间接 has_many 关联的名称?
【发布时间】: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.statesProduct访问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: :statesource 应指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


【解决方案1】:

是的,有办法。做:

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

【讨论】:

  • 甜蜜!它工作 \o/。非常感谢你,@jvillian!
猜你喜欢
  • 1970-01-01
  • 1970-01-01
  • 1970-01-01
  • 1970-01-01
  • 1970-01-01
  • 1970-01-01
  • 2016-01-05
  • 1970-01-01
  • 2014-07-06
相关资源
最近更新 更多