matiasfha
matiasfha

Reputation: 1290

Rails, Mongoid, Devise User profiles

I'm new to rails (rails 3) and I am learning in practice.

I want to create a User-profile relation. I have created a User model with devise, and that is working well. Then I created a Profile model. The idea is to register an user and the show information about his profile and if the user wants, complete the profile.

But, the profile is related with posts. So, I need to create an empty profile with the register action of the user.

How can I do that?

My idea is to change the UsersController#create method to build the empty profile, but i don't know how.

My models

class User
    include Mongoid::Document
    devise  :database_authenticatable, :registerable, :token_authenticable,        
            :omniauthable,
             :recoverable, :rememberable, :trackable, :validatable
    field :username
    key :username
    embeds_one :profile
    attr_accessible :username,:password,:password_confirmation,:remember_me

class Profile
    include Mongoid::Document
    field :name
    field :lastname
    ...
    ...
    embedded_in :user, :inverse_of => :profiles
    referenced_many :posts

Some idea?

Upvotes: 2

Views: 1947

Answers (1)

Shane Bauer
Shane Bauer

Reputation: 263

It looks like you're only embedding one profile (embeds_one :profile). It should be user.profile, not user.profiles. Also, user.profile will return an instance of that document, not an array of many documents.

You could do something like this in your controller.

user.profile.create(... put any params here ...)

In your view you would then display

<h2>Welcome <%[email protected] %></h2>

You also need to change

embedded_in :user, :inverse_of => :profiles

to

embedded_in :user, :inverse_of => :profile

To see if the user has a profile or not, just see if user.profile returns nil.

Upvotes: 2

Related Questions