How can assign value on rails model

Advertisements

I am trying to set the value in the User model on the after_create callback, but one of my model field values is not getting set.

User.find_or_create_by!(company_id: 1)

Model

before_create: set_value

def set_value
 self.assign_attributes(
   company_name: self.company.name
   location: self.company.location
 )
end

Location values are set in the user model, but company_name is always nil. I don’t know where I am making a mistake. When I do User.last, I am getting all values except the company_name, and the company name is also present in self.company.name

When I try to create new model from rails console and set the value to company_name it throws an error

SystemStackError: stack level too deep

>Solution :

I think according to this error, SystemStackError, you have the same-name method in your model as setter. If you have, then change the name of the method; the issue will be resolved, and the value company_name will also be set on the after_create callback.

Leave a ReplyCancel reply