in my app my user model has an instance_id which is related to the Instance model.
Use开发者_如何学Pythonr:
id, email, instance_id
Instance:
id, domain
so if the email is bob@yahoo.com, his instance_id is 5, as (5, yahoo.com) is in the instance table.
What I want to do is, every time a user record is updated, check to make sure that the email matches the right domain. So i have the following:
after_save :assign_user_to_instance
def assign_user_to_instance
domain = email.split("@").last
user_instance = Instance.find_or_create_by_domain domain
update_attribute(:instance_id, user_instance.id)
end
Problem is when this runs, it goes in a crazy loop of updates to the DB and never ends. What's the right way to achieve this?
Thanks
Try using a 'before_save' instead of an 'after_save'.
精彩评论