开发者

Rails - How to have a method run anytime a record is updated

开发者 https://www.devze.com 2023-03-05 11:21 出处:网络
in my app my user model has an instance_id which is related to the Instance model. Use开发者_如何学Pythonr:

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'.

0

精彩评论

暂无评论...
验证码 换一张
取 消