sandre89
sandre89

Reputation: 5918

Rails has_many :through #new doesn't set associations on new record

As per the Rails docs, one can use has_many :through as a shortcut:

The has_many :through association is also useful for setting up "shortcuts" through nested has_many associations. For example, if a document has many sections, and a section has many paragraphs, you may sometimes want to get a simple collection of all paragraphs in the document.

So let's say we have this code:

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

Based on this, if I run user.settings.new, I get a new Setting instance with user_id set to user.id.

That's great. But if I run sub_user.settings.new, I get a new Setting instance that doesn't have user_id set to sub_user.user.id.

Is this expected behavior?

Upvotes: 0

Views: 302

Answers (1)

arieljuod
arieljuod

Reputation: 15848

I wouldn't use has_many through: for that, delegate looks like the best idea https://apidock.com/rails/Module/delegate

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

Your current code is not what has_many through is for, check the docks, the relations are different https://guides.rubyonrails.org/association_basics.html#the-has-many-through-association

Upvotes: 0

Related Questions