slabounty
slabounty

Reputation: 704

Rails 3.1 - find_or_create_by Not Saving

I have this code ...

    recipient = User.find_or_create_by_email(params[:recipient_email],
        { :password => 'password',
        :password_confirmation => 'password',
        :first_name => 'First',
        :last_name => 'Last',
        :active => false })

which doesn't work. The recipient isn't saved in the database as it should be. However this ...

    recipient = User.find_or_create_by_email(params[:recipient_email],
        { :password => 'password',
        :password_confirmation => 'password',
        :first_name => 'First',
        :last_name => 'Last'})

does work in that it creates the recipient and saves it in the database, but the :active flag is now set to the default true.

In the User model I have ...

attr_accessible :first_name, :last_name, :email, :password, :password_confirmation, :active

and

validates :active, :presence => true

Any ideas as to what's going on here?

Upvotes: 1

Views: 1744

Answers (1)

pdu
pdu

Reputation: 10413

Your :active is either true or false (or nil unless you defined a default value in your migration file). Maybe false is interpreted as non-present, I don't really know. BUT this is how I would do this:

Put t.boolean :active, :default => false in your file (or if you need to create a migration, do change_column :table, :active, :boolean, :default => false) and then remove your validation.

Every user is now saved as false unless you provide a param with a different value. If most of your users should be true (so the whole thingm, but vice-versa), then change it so. This makes your validation needless.

Hope I got the point of your problem.. otherwise, ignore me.

Upvotes: 1

Related Questions