Gamal Tawaf
Gamal Tawaf

Reputation: 125

update_attributes validation fails though values are correct

I have in my model

class Account < ActiveRecord::Base
 validates_length_of :amount, :in 1..255, :on => update, :if => Proc.new { |a| false if a.id == nil;a.amount.blank? }
 validates_length_of :name, :in 1..255, :on => update, :if => Proc.new { |a| false if a.id == nil;a.name.blank? }, :unless => user_has_amount?

end 

when I comment out the if condition, it works fine but with them validation fails which is confusing. I know that the validation should only run if the proc returns true or unless returns false in my controller I have

@account.update_attributes({:name => "king", :amount => "1223"}

the save fails and when I check errors I get

@account.errors.details
{:name =>[{:error=>:too_short, :count=>1}], :amount =>[{:error=>:too_short, :count=>1}]}

Strong Params are not an issue because I have def self.params params.require(:account).permit! end

I have no idea why it fails though the value are present and correct.

Upvotes: 0

Views: 1286

Answers (3)

Gamal Tawaf
Gamal Tawaf

Reputation: 125

The issue that was happening was for one reason. The code was inheriting from a class that had:

slef.reload 

in one of the function that were being called during validations.

so every time we try to update the update failed because once that validation was hit it reloaded the original values from database and ignored new values which if old values are empty is just a head scratcher.

Thanks everyone for the help

Upvotes: 0

David Weber
David Weber

Reputation: 479

Check your strong parameters. Your error tells you that something is wrong before you get to validation: :name =>[{:error=>:too_short, :count=>1}] This is saying that the minimum string count is 1 but that your string is not even that long. Here is the docs on that.

You can try: Account.find(1).update_attributes({:name => "king", :amount => "1223"} to see if @account is not being set properly.

You can also customize the language on your errors to help further:

validates_length_of : name, within: 1..255, too_long: 'pick a shorter name', too_short: 'pick a longer name'

Upvotes: 0

Mikhail Katrin
Mikhail Katrin

Reputation: 2384

Try this the following:

class Account < ActiveRecord::Base
    validates :amount, length: { in: 1..255 }, on: :update
    validates :name, length: { in: 1..255 }, on: :update
end

Upvotes: 0

Related Questions