0

user.rb

after_initialize :init

private

    def init
        self.name ||= 'Bob'
    end

irb

irb> User.select('id')
(Object doesn't support #inspect)

If I change the callback to before_validation then the above query works.

Ideally I would like to be able to keep the initialization in after_initialize. Is there a way to achieve this?

I would prefer not to have to override the initialize method.

2
  • Have you tried doing just e.g., User.first? I don't know if select actually (or fully) instantiates an AR::Base object... Commented Dec 20, 2014 at 23:15
  • What exactly are you trying to do that makes you think after_initialize is a solution? Commented Dec 20, 2014 at 23:17

1 Answer 1

-1

The posted code is trying to set the name every time a user is instantiated (such as User.new, User.first, User.all )

If you intend to save the record with name = "Bob" when name is nil, do it in before_validation, or after_validation.

If you intend to merely return "Bob" when name is nil, do it in the getter:

  def name
    @name ||= "Bob"
  end
Sign up to request clarification or add additional context in comments.

2 Comments

Why the negative vote? I'll like to understand if I misunderstood the question, my answer is wrong, what I said is wrong or it is against the rules or ?
Thanks for your answer. I have yet to determine whether your answer will be suitable in my situation. Anyway, I didn't downvote - and I hate it when people downvote without writing their reasoning in a comment.

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.