westonganger / protected_attributes_continued

The community continued version of protected_attributes for Rails 5+
MIT License
45 stars 33 forks source link

Calling `first_or_initialize` on an `AssociationRelation` raises `ArgumentError` in Rails 6 #19

Closed aergonaut closed 4 years ago

aergonaut commented 4 years ago

In Rails 6, the signature of the methods build, create, and create! for AssociationRelation changed so that they no longer accept *args, but rather accept only 1 argument.

This causes an ArgumentError to be raised when using methods like first_or_initialize on an AssociationRelation. I had never heard of this class before, but apparently it is the class that you get when you chain a where onto an association method, like: user.comments.where("1=1").

I have reproduced this issue with the following script:

require "bundler/inline"

gemfile(true) do
  source "https://rubygems.org"

  gem "activerecord", "~> 6"
  gem "sqlite3"
  gem "protected_attributes_continued", "1.6.0"
end

require "active_record"

ActiveRecord::Base.establish_connection adapter: "sqlite3", database: ":memory:"

ActiveRecord::Schema.define do
  create_table :users, force: true do
  end

  create_table :comments, force: true do |t|
    t.belongs_to :user
  end
end

class User < ActiveRecord::Base
  has_many :comments
end

class Comment < ActiveRecord::Base
  belongs_to :user
end

User.new.comments.where("1=1").first_or_initialize

I fixed this at my job by adding a patch to AssociationRelation. If it's alright, I would like to upstream that patch to this gem. I can raise a PR if that sounds like a good idea.

westonganger commented 4 years ago

Thanks for reporting this. Would love a PR for this.

aergonaut commented 4 years ago

@westonganger Raised #20. Happy to help.