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

Fixes validations with validates_uniqueness_of #470

Closed
wants to merge 1 commit into from

Conversation

artplan1
Copy link
Contributor

Hi, we're having issues with uniqueness validations done with validates_uniqueness_of.
I assume that constant in validates_uniqueness_of is still points to default rails validator.

    Failure/Error: model_class.create(attribute1 => "foo")

     ActiveRecord::StatementInvalid:
       PG::UndefinedColumn: ERROR:  column container_posts.title does not exist
       LINE 1: SELECT 1 AS one FROM "container_posts" WHERE "container_post...

I came up with straightforward solution, but I believe there are better solutions.

@shioyama
Copy link
Owner

Thanks for the PR! ❤️

I came up with straightforward solution, but I believe there are better solutions.

Hmm well I think it's fairly safe to do it this way, since this only overrides the method on the class and not other classes.

For reference, the reason the code has const_get/const_set is because validates looks for the constant UniquenessValidator and will prefer the model namespace if there is a constant defined there:

https://github.com/shioyama/rails/blob/5262ec59002e461b2fdb8cb81f0ac1623b1cd2fd/activemodel/lib/active_model/validations/validates.rb#L119

            validator = key.include?("::") ? key.constantize : const_get(key)

So by defining the constant, we can selectively override the default uniqueness validator on this model only. If that wasn't possible we'd have to override validates which would be much more tricky.

But validates_uniqueness_of can easily be overridden on the model since it's just a one-line method. So I think this is a 👍 solution.

model_class.create(attribute1 => "foo")
expect(model_class.new(attribute1 => "foo")).not_to be_valid
end
end
Copy link
Owner

Choose a reason for hiding this comment

The reason will be displayed to describe this comment to others. Learn more.

Thanks for the test!


def self.validates_uniqueness_of(*attr_names)
validates_with(UniquenessValidator, _merge_attributes(attr_names))
end
Copy link
Owner

Choose a reason for hiding this comment

The reason will be displayed to describe this comment to others. Learn more.

LGTM 👍

@shioyama shioyama closed this in 92c4480 Dec 12, 2020
@artplan1 artplan1 deleted the validates-uniqueness-of branch December 12, 2020 10:00
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 this pull request may close these issues.

2 participants