ruby - Rails 3: Get current user_id to save in different model -


i have user , article model. when save article need save user created article therefore need id. need know user created it?

my article.rb

class article < activerecord::base   belongs_to :user   attr_accessible :title, :description, :user_id    validates_length_of :title, :minimum => 5 end 

my articles_controller.rb

def create     @article = article.new(params[:article])      respond_to |format|       if @article.save         format.html { redirect_to @article, notice: 'article created.' }         format.json { render json: @article, status: :created, location: @article }       else         format.html { render action: "new" }         format.json { render json: @article.errors, status: :unprocessable_entity }       end     end   end 

my article _form

<div class="field">     <%= f.label :title %><br />     <%= f.text_field :title %>   </div>   <div class="field">     <%= f.label :description %><br />     <%= f.text_area :description %>   </div> 

so how set user_id in article model correctly? 1 has session! have helper_method in application_controller not sure how use it.

class applicationcontroller < actioncontroller::base   protect_from_forgery    helper_method :current_user    private   def current_user     @current_user ||= user.find(session[:user_id]) if session[:user_id]   end end 

thanks help!

you should in controller:

def create   @article = current_user.articles.build(params[:article])   ... end 

or

def create   @article = article.new(params[:article].merge(:user_id => current_user.id))   ... end 

but prefer first one.


Comments

Popular posts from this blog

linux - xterm copying to CLIPBOARD using copy-selection causes automatic updating of CLIPBOARD upon mouse selection -

c++ - qgraphicsview horizontal scrolling always has a vertical delta -