【问题标题】:Rails has_many :through #new doesn't set associations on new recordRails has_many :through #new 不会在新记录上设置关联
【发布时间】:2018-09-11 23:18:25
【问题描述】:

根据 Rails 文档,可以使用 has_many :through 作为快捷方式:

has_many :through 关联对于设置也很有用 通过嵌套的 has_many 关联的“快捷方式”。例如,如果一个 文档有很多节,一个节有很多段落,你可以 有时想要获取所有段落的简单集合 文档。

假设我们有这段代码:

class User < ApplicationRecord
  has_many :sub_users
  has_many :settings
end

class SubUser < ApplicationRecord
  belongs_to :user
  has_many :settings, through: :user
end

class Setting < ApplicationRecord
  belongs_to :user
end

基于此,如果我运行user.settings.new,我会得到一个新的Setting 实例,其中user_id 设置为user.id

那太好了。但是如果我运行sub_user.settings.new,我会得到一个新的Setting 实例,它没有将user_id 设置为sub_user.user.id

这是预期的行为吗?

【问题讨论】:

    标签: ruby-on-rails


    【解决方案1】:

    我不会为此使用 has_many through:delegate 看起来是最好的主意 https://apidock.com/rails/Module/delegate

    class SubUser < ApplicationRecord
      belongs_to :user
      delegate :settings, to: :user
    end
    

    您当前的代码不是has_many through 的用途,检查码头,关系不同https://guides.rubyonrails.org/association_basics.html#the-has-many-through-association

    【讨论】:

    • 我曾经使用委托,但是一旦您需要 SubUser.joins(:settings) 或简单的.includes 以避免 n+1 查询,事情就会开始中断。如果您使用delegate,您将错过 ActiveRecord 关联的所有好处;话虽如此,如果 Rails 不够聪明,无法使用正确的 ID 预先填充 sub_user.settings.new,我认为这是一个很小的代价,因为使用我的解决方案(这是官方文档的一部分 - 请参阅引用的部分) 我至少可以使用.joins.includes
    • 您的问题引用是关于has_many 模型和has_many 模型的模型。您的设置是 belongs_to,然后是 has_many 模型。不一样(你是说那句话吗?)。无论如何,与委托,我认为你可以使用连接或包含,检查嵌套连接的文档guides.rubyonrails.org/…
    • 不,您不能使用连接,也不能使用委托。
    猜你喜欢
    • 1970-01-01
    • 1970-01-01
    • 2011-04-21
    • 1970-01-01
    • 2011-02-17
    • 2014-02-27
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    相关资源
    最近更新 更多