1

I have two fields, first_name and brand_name. User enters first_name during sign in. And if he is an owner, he enters brand_name. brand_name by default equals first_name when the user creates an account. The user can change it later.

For this I wrote this method in the User model,

def brand_name
    first_name
end

But it sets brand_name to first_name though user enters different brand_name. I tried doing in this way:

def brand_name
    if brand_name.nil?
      first_name
    else
      brand_name
    end
end

But gives error- SystemStackError:

stack level too deep

Can anybody help in how to do this?

1 Answer 1

6

Your method is calling itself, which leads to infinite recursion. Rewrite your method like so:

def brand_name
  self[:brand_name].present? ? self[:brand_name] : first_name
end
Sign up to request clarification or add additional context in comments.

4 Comments

it is not taking first name if brand_name is blank. It displays brand_name if brand name is present. Else prints nothing.
That wasn't entirely clear from your question, but I went ahead and updated my answer to handle the case where brand name is set to empty string. You may want to consider validating the brand_name to have length > 0.
oh, m sorry for that, couldn't explain properly. Thanks for editing question! The solution is working :-) One doubt, y 'self' is necessary? not getting how to use it and when to use.
self was necessary here because I used the [] method to access an ActiveRecord attribute dynamically. This would be equivalent to read_attribute(:brand_name), but I prefer this form because it's shorter.

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.