ubique
ubique

Reputation: 1212

Rails and Devise - Add a Field To Log-In

I have set up a blog with secure log-in using the Devise plugin and its working well. I'm going to add an additional 'username' field at sign-up and article posts will then display this info. How do I achieve this so the username goes into the db - any code help would be appreciated?

User names will need to be unique but I will look into this later.

Upvotes: 3

Views: 686

Answers (3)

colinross
colinross

Reputation: 2085

  • add belongs_to :user in your article.rb and has_many :articles to your user.rb
  • update your migration of article to include a user_id:integer field (or use t.references :user)
  • update your ArticlesController#create action to use current_user.create_article or build_article
  • be sure to invoke the authenticate_user! before_filter for the :create action before_filter :authenticate_user!, only => :only => [:new, :create, :edit, :update, :destroy]

ref: http://guides.rubyonrails.org/association_basics.html

Upvotes: 0

Lucas
Lucas

Reputation: 2886

Okay so you have 2 questions in the same topic.

The first one has been answered and you followed these steps: Add custom fields to devise

Then for your next question: the problem isn't the user but @article because this variable is nil. So Rails can't find the User related to something that is nil.

You should post your controller and your _article view so I can help further.

Also I don't understand what you meant by :

I changed the object from 'email' to 'username' to stop it showing the submitters email address in the article

..You can choose whatever you want to display without replacing anything. If you want to display the user's username, just do user.username

Upvotes: 0

Andrei S
Andrei S

Reputation: 6516

As the Devise wiki sez:

Create a migration

rails generate migration add_username_to_users username:string

Run the migration

rake db:migrate

Modify the User model and add username to attr_accessible

 attr_accessible :username

more info here

For uniqueness you could just do a validation on the User model

Hope this helps!

Upvotes: 8

Related Questions