0

I have model user.rb like below:

class User < ActiveRecord::Base

before_save :set_default

    def set_default
        self[:is_admin] || 0 
        self[:is_active] || 1   
    end 
end

Now when i create u new user , it inserts is_admin = null , is_active = null . While when i update user and send parameters is_admin= true , is_active = true or whatever values it updates it correctly . I did some R&D and found that i should do the following

def set_default
        self.is_admin || 0 
        self.is_active || 1   
end 

Now the case becomes totally alternate . Means now values are inserting correctly on creation . but updation makes no difference . I also tried it with the following

def set_default
        self.is_admin ||= 0 
        self.is_active ||= 1   
end 

But still no help . Kindly explain what's going on . Any help will be appreciated .

2
  • hey I've never seen that syntax before! self.is_admin] can you tell me what that square bracket does? and what should i google to get more info on that? Commented Feb 24, 2016 at 15:47
  • @Harfangk it's not syntactically valid Ruby actually. So... nothing :) Commented Feb 24, 2016 at 15:55

1 Answer 1

1

If you always want those fields to start with that default data, I would move your defaults to the schema.

def change
  create_table :users do |t|
    t.boolean :is_admin, default: false, null: false
    t.boolean :is_active, default: true, null: false
    ...
  end
end

This will set the defaults on your users table without needing the extra cost/complication of a callback. This will also nicely blow up if you try to set either of those to nil which would produce unexpected behaviors in your application.

Hope that helps.

Sign up to request clarification or add additional context in comments.

3 Comments

Thanks for fixing the typo j-dexx :)
voted for the fix , but dear i think that's not the solution . I mean why that odd behaviour
Can you clarify a little? If it sets it properly on creation, then updating it would disregard both of those statements because ||= would only ever set those values if they are nil. Not sure if thats what you are asking though.

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.