Search code examples
ruby-on-rails-3validationactiverecordclient-side-validation

validates_inclusion_of Rails 3 with a query not working as expected


I am newish to Rails and i am facing a prblem. I have

Models

Model1
id: integer
account_id: integer

Account
id: integer

I have a validation in the Model1 as follows,

Model Code:

validates :account_id, :inclusion => { :in => Account.find(:all).collect(&:id)}

I use a dropdown for View Code:

<%= f.select :account_id, @accounts.collect {|acc| [acc.name, acc.id]}, {:prompt => 'Select Account' }, { :selected => @defaultaccount, :class => 'selectwidth' } %>

I am using client side validations to validate the fields before submitting the form. I am using Heroku to deploy my app.

I create an account first and then from the form i try to create a new model1. The drop down is populated with all the accounts that i have. Then i select an account that i created from the dropdown, the client side validations comes into effect and says "is not valid" which is the error message for validates_inclusion_of as if the account never exists. Not sure what ishappening and i checked the database and the account is created which is why the dropdown is loaded with accounts in the first place.

I change the validates_inclusion_of to rails 3 validates :account_id, :inclusion => { :in => {} } syntax and redeploy. Now i try to select that account in the new model1 form, The drop down does not show an error for the account that was previously created.

So then i created a new account and tried to create a new model1 for the new account the validation failure resurfaces.

So its like a cache issue ? Is it a client side validations issue ? I did everything i can to try and find what the issues is but i am out of ideas on what is happening.

So everytime i create an account it expects me redeploy which kills what the application does. How do i get rid of this problem ? Not really sure what is happening.

Config, Rails 3 Deployed in Heroku uses Asset pipeline

Gems: Client Side Validations Kaminari


Solution

  • It's not working as you want because the :in => Account.find(:all).collect(&:id) it's evaluated just one time in production mode, when Rails loads the class. I confess I don't understand the reason behind such a validation. Anyway, you have to use a custom validator if you really want to achieve that.