Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

How to pass Devise's current_user as user_id?

I'm practicing my Ruby on Rails by creating a simple application where users can sign up (using Devise) and post articles.

After installing Devise, I go ahead and generate a scaffold for the articles

 rails g scaffold article title:string article:text user_id:integer

Then I create the Devise user controller

rails generate devise User

My article controller:

class Article < ActiveRecord::Base
    belongs_to :user
end

My user controller:

class User < ActiveRecord::Base
  has_many :articles

  devise :database_authenticatable, :registerable,
         :recoverable, :rememberable, :trackable, :validatable

  attr_accessible :email, :password, :password_confirmation, :remember_me
end

Now my question is: how do you make it so that user_id in http://localhost:3000/articles/new/ is automatically current_user.id?

Also, in http://localhost:3000/articles/ the user should only be able to view the articles associated with their user_id, not anyone elses. What changes to the articles controller should I make to do this?

It's my first time posting here at Stack Overflow and your help would be appreciated.. Thanks a bunch!

EDIT found the solution to the first question, for future reference.

I put

<%= f.hidden_field :user_id %> 

in _form.html.erb, and

def create
    @article.user_id = current_user.id 
    ...
end

to my article controller. This is successfully passing the current_user.id as the article's user_id perfectly.

like image 728
cdotfeli Avatar asked Dec 12 '11 09:12

cdotfeli


2 Answers

Now my question is: how do you make it so that user_id in http://localhost:3000/articles/new/ is automatically current_user.id?

You should add to articles_controller's "def new" this line @ask.user_id = current_user.id

so then form_for @ask asks for the user_id property of @ask and displays it. But I do not recommend doing this in a real-world app, where you probably would handle this step in "def create" of `articles_controller

`Also, in http://localhost:3000/articles/ the user should only be able to view the articles associated with their user_id, not anyone elses. What changes to the articles controller should I make to do this?

inside articles_controller's def index, change to @articles = Article.where(user_id:current_user.id). Note that you should also add a before_filter :require_user to make sure that current_user is not nil.

like image 178
Minqi Pan Avatar answered Nov 06 '22 21:11

Minqi Pan


In your ArticleController#new action add the following line:
@article = current_user.articles.build

As for your index action:
@articles = current_user.articles

like image 27
Faisal Avatar answered Nov 06 '22 20:11

Faisal