Skip to content
New issue

Have a question about this project? Sign up for a free GitHub account to open an issue and contact its maintainers and the community.

By clicking “Sign up for GitHub”, you agree to our terms of service and privacy statement. We’ll occasionally send you account related emails.

Already on GitHub? Sign in to your account

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

Closed
aergonaut opened this issue Oct 23, 2020 · 2 comments · Fixed by #20
Closed

Comments

@aergonaut
Copy link
Contributor

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
Copy link
Owner

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

@aergonaut
Copy link
Contributor Author

@westonganger Raised #20. Happy to help.

Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment
Labels
None yet
Projects
None yet
Development

Successfully merging a pull request may close this issue.

2 participants