0
votes

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.

3
Check the account_params to check that these parameters are not restricted by strong parameters. - Acacia
Your model code is syntactically incorrect. I assume you retyped it by hand and made a few typos. Anyway, please correct it, so we could test the code ourselves. Also, could you please provide schema.rb for accounts table - Nikita Misharin
What if you do this : validates :amount, length: { in: 6..20 }, on: :update. instead of validates_length_of. I've found it in rails documentation : Validations Helpers -> Length - Diego Patricio Aguilef Sánchez
That was the original statement and I was still getting the same error. - Gamal Tawaf
I have updated the question - Gamal Tawaf

3 Answers

0
votes

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
0
votes

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'
0
votes

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