简体   繁体   中英

Create a model observer that creates an associated model relationship

I have the following models:

User (id,email,name)
Group (id,domain)
GroupUser (id, group_id, user_id)

What I would like to do is anytime a user is created. Find the user's email domain and automatically create the Group and the joining GroupUser record.

After performing:

u = User.new
u.email = 'bob@ge.com'
u.name = "my name"

What is the right way in the user model/observer to make this happen?

Thanks

You should create a UserObserver rails g observer UserObserver and define an action:

def after_create(user)
    domain = user.email.split("@").last
    if (group = Group.where(domain: domain)).any?
        GroupUser.create(group.id, user.id)
    else
        group = Group.create(domain)
        GroupUser.create(group.id, user.id)
    end
end

I think this might be helpful.

UPDATE: Sorry, there was a problem with code. Fixed it.

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM