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.
You should add to articles_controller’s “def new” this line
@ask.user_id = current_user.id
so then
form_for @askasks for theuser_idproperty of@askand 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_controllerinside
articles_controller‘sdef index, change to@articles = Article.where(user_id:current_user.id). Note that you should also add abefore_filter :require_userto make sure thatcurrent_useris not nil.