Creating a site with rails and need guidance with user profile and devise

I am trying to create a rails app.I am new to this so just playing around.

So far, i have setup a devise authetication system. which created a user model. I have a page model and controller. Now i am wondering how i create a user profile ?

Also how do i get the values like user's name, email and stuff? What should i generate? A user controller or if i generate a UserProfile model then how can i get the values like user email when the user signs up using devise.

1 Answer

  1. Lawrence- Reply

    2019-11-14

    You can add all needed fields to the model , generated by devise (e.g. User). If you want to keep all data in separate model(UserProfile), then you need to create has_one/belongs_to association:

    class User < ActiveRecord::Base
        has_one :user_profile
        # ... Some other stuff here
    end
    
    class UserProfile < ActiveRecord::Base
       belongs_to :user
       # ... 
    end
    

    To get email for UserProfile you can:

    profile = UserProfile.first
    email = profile.user.email
    

    To get UserProfile from User object:

    user = User.first
    profile = user.user_profile
    

    To make it possible to store information about page author you should use has_many/belongs_to association:

        class User < ActiveRecord::Base
            has_many :pages
            # ... Some other stuff here
        end
    
        class Page < ActiveRecord::Base
            belongs_to :user
            # ... Some other stuff here
        end
    

    In some of views for Page model you can display author like:

    Page author is <%= @page.user.user_profile.name %>
    

    Or, if you decided to add fields directly to User model

    Page author is <%= @page.user.name %>
    

Leave a Reply

Your email address will not be published. Required fields are marked *

You can use these HTML tags and attributes <a href="" title=""> <abbr title=""> <acronym title=""> <b> <blockquote cite=""> <cite> <code> <del datetime=""> <em> <i> <q cite=""> <strike> <strong>