rails: accepts_nested_attributes_for breaks the uniqueness with scope validation
Hi All, I think for the following configuration accepts_nested_attributes_for + validation seems to be broken!! Rails 4.2.1 Ruby 2.1.3
class Country < ActiveRecord::Base
has_many :cities, dependent: :destroy
accepts_nested_attributes_for :cities
end
class City < ActiveRecord::Base
belongs_to :country
validates :language , uniqueness: { scope: :country_id }
end
country = Country.new(description:'abc', language: 'en-US', cities:[City.new(language: 'en-US', text: 'abc'), City.new(language: 'en-US', text: 'abc')])
country.save!
works!!
c1 = City.new(language: 'en-US', text: 'abc', country_id: 1)
c1.save!
c2 = City.new(language: 'en-US', text: 'xyz', country_id: 1)
c2.save! #does not work
Here is executable report https://gist.github.com/spurnaye/0ab33d62dc1f12751ee0 Appreciate efforts on this!
About this issue
- Original URL
- State: open
- Created 11 years ago
- Reactions: 66
- Comments: 74 (15 by maintainers)
How is this not fixed yet? Nearly 5 years later…
Bumping in 2020. Any fix?
I’ve found a (really hacky) workaround. I abuse the
ifproc to assign the foreign key.Now everything works as expected.
Can reproduce on Rails 5 beta 3
Problem still exists with Rails 6 and Ruby 2.6.5. Please fix this.
In my case I’m calling
.valid?, and so the associated models are not saved to the database at all. I still think validation should fail though. I think the only way for this to work would be for the validation to check if the scope refers to an association, and if so validate uniqueness against sibling objects models in memory.For example:
In this case I’d imagine that when each Child is validated, the UniquenessValidator would look up
parent.childrenand see if any of the other children share the same name.Looking at the code forUniquenessValidator at the moment it’s hard-coded to work using
where()(see line 95). That’s fine when individual models are being created or updated, but won’t work when you’re creating multiple models at once as we do with accepts nested attributes.I have the same issue in rails 5.0.0.1.
There is no other solution than setting a unique index on 2 columns and handle the ActiveRecord::RecordNotUnique exception in the controller?
I’ve gone with @catogonzalez 's solution, adapted to be reusable across different classes.
I am using this alongside ActiveRecord’s validator in the classes in question, since the nested_uniqueness validator doesn’t cover cases where records are created without using accepts_nested_attributes_for:
My not-so-hacky solution that might as well be converted to a custom validator if you have to use it in many places:
The same issue persists in rails 4.2.7 as well
Same issue with Rails 5.2.3 on Ruby 2.6.3. Please fix.
Just commenting here to say that I also am facing this issue with rails 5.2.2
Updated reproduction script
The key issue is that the validation of the associated record is called before saving the parent record which leads into not finding the uniqueness validation error . What we could do is to define a set of validations (just uniqueness for now) which should run after the parent record has been saved and if any of such validation exists we should call validate on the associated record also after save/update and rollback the transaction in case of validation error.
I’d like some feedback from the core team about this proposal.
Fix please
Not that I expected anything else, but the problem continues to exist in Rails 6.0 (beta).
I modify @Jaroost 's solution a little bit to work with scope:
So that you can do something like this on your model:
validates_uniqueness :teacher_id, scope: [:semester_id, :class_id]Verified this on Rails 6.0.3.2. Would be great if this is addressed.
I updated @jaroost’s final solution with @thuhuongly’s changes, plus the following:
I made the Rails 5 error key configurable; obviously whatever error key you use, either your own or a custom one, needs to be added to i18n either at the base activemodel level or in your specific model:
en.errors.messages.<your key>en.activerecord.errors.models.<your_model>.attributes.<your nested attribute>.<your key>Usage is like this:
Agreed, there still doesn’t seem to be a fix for it. I have a model with a nested form and then I’m also trying to add validations for presence and other data quality in the model thats being nested, but to no avail.
In my use case I could do something along the lines of throwing some errors in the controller for validation, but its a little sloppy. Could potentially just lax up on validations.
@rafaelfranca do you have any particular thoughts on the best way to address this? I could contribute a PR given a bit of direction.
I am using Rails 6, and updated @armchairdj solution with case sensitivity
Not fixed 👍
Please fix asap.
Please fix this
Hi @djezzzl it’s a great gem, and it works in some cases, but just FYI not for polymorphic belongs_to (obviously since there is no FK). We still need a general solution there.
Still happening on Rails 5.2.1; Most workarounds in this topic is pretty hacky. I might as well drop accept
accepts_nested_attributes_forall together and create the parent and child separately.@thuhuongly This doesn’t seem to work on rails 5.1.5. The “value.map” throws an exception as it’s expecting an array but a string is encountered.
I having this issue on rails 4.2.3
I’ve ended up with this gem https://github.com/toptal/database_validations#rescue-option
Works fine with create / update template record
@spurnaye This is how I worked around it:
I wouldn’t count on your workaround being temporary. This issue has been open for four years and two major releases. I’m not sure if this will ever be fixed.
hello everyone, i decided to implement a simple after_validation on the nested model.
Something like in restricted_endpoint model
validates :code, presence: true, uniqueness: { scope: :client } before_save :restricted_code_should_be_uniq, on: :create
private def restricted_code_should_be_uniq unless client.restricted_endpoints.where(code: code).blank? self.errors.add(:code, :invalid) raise ActiveRecord::RecordInvalid.new(self) end end
this is only temporary until the problem is solved
I am also facing this bug within
Rails 5.1.5. Within this stackoverflow post I try to explain my problem and provide a simple solution using aunique database indexand aaround_savecallback.I still have this problem in Rails 5.0.5, here is a post i made in StackOverflow describing with details.
Confirming presence of issue in Rails 5.0.1 as well
I also have the same issue on rails 5.0.0.1.
Here’s my sample code:
class PeopleGroupItem < ApplicationRecordbelongs_to :people_groupvalidates :type, presence: true, uniqueness: {scope: :people_group, message: 'combination already used'}validates :value, presence: trueendI also tried scope: :group_id but to no avail.
However, the validation of the presence requirement does work. It’s just the uniqueness check which is ignored.
Can reproduce on master – the only error I’m seeing is with the last test, where the new
Countryis being created. Would you be willing to do a little bit of some sourcediving and try and figure out where this bug is introduced, and how it can be solved?I having this issue on rails 4.2.5…
TL;DR Child uniqueness validation should be done only after parent
INSERTed.I have similar issue, and I found that validations with
scopeare done before the parent record is saved, and it checks forNULLvalue, instead of real id value that will be saved only afterINSERTis completed.