Brett
Brett

Reputation: 162

Rails: Building a has_one relationship in a model with Omniauth

I have a User model that has_one Profile (belongs_to User). For simplicity I'll just say the profile has a location field and an occupation field.

I'm using Omniauth to create Users but I would also like to create the attached Profile at the same time. Currently my create from omniauth method is as follows:

def self.create_from_omniauth(omniauth_data)
  full_name = omniauth_data["info"]["name"].split(" ")
  User.create(
       provider: omniauth_data["provider"],
       uid: omniauth_data["uid"],
       first_name: full_name[0],
       last_name: full_name[1],
       email: omniauth_data["info"]["email"],
       password: SecureRandom.hex(16)
  )
end

I'm wondering how I should include the building of the profile in that. I know with has_one I have access to the build_profile method but I also want to ensure that it is properly connected to my User object. Any insight into how I should reformat that create_from_omniauth action to properly build the associated Profile alongside the User object would be extremely helpful.

Upvotes: 0

Views: 53

Answers (1)

codigomonstruo
codigomonstruo

Reputation: 1091

The easier way to do what you want is use the users#show action for the Profile. Instead of creating a Profile model with a Profile table in the database (wasting of memory), why not just use the show for your users as profile. In that case you can rename the route for your show action as profile.

Upvotes: 1

Related Questions