2013-05-09 47 views
1

我有一个用户和一个文章模型。 当我保存一篇文章时,我还需要保存哪个用户创建了文章,因此我需要他的ID。所以我需要知道哪个用户创建了它?Rails 3:获取当前的user_id以保存在不同的模型中

我article.rb

class Article < ActiveRecord::Base 
    belongs_to :user 
    attr_accessible :title, :description, :user_id 

    validates_length_of :title, :minimum => 5 
end 

我articles_controller.rb

def create 
    @article = Article.new(params[:article]) 

    respond_to do |format| 
     if @article.save 
     format.html { redirect_to @article, notice: 'Article was successfully 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 

我的文章_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> 

所以,我如何设置正确的文章模型user_ID的?我希望有一个会议的人!我在application_controller中有一个helper_method但我不确定如何使用它。

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 

感谢您的帮助!

+0

退房这样的回答: http://stackoverflow.com/questions/3742785/rails-3-devise-current-user-is-not-accessible-in-a-model#3742981 – Tilo 2013-05-09 22:12:38

回答

4

你应该做这样的事情在你的控制器:

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 

但我宁愿第一个。

+0

我提交几分钟前的答案是不同的,但我也喜欢@ jokklan的第一个选项。这将利用用户和文章之间的关系来创建一个新文章,并将其user_id属性自动设置为当前登录的用户。 – 2013-05-09 22:29:25

+0

是在文章模型中建立一个方法吗? – user1354743 2013-05-10 09:43:51

+2

build是一个自动生成的方法,有关更多信息,请看看这里:http://api.rubyonrails.org/classes/ActiveRecord/Associations/ClassMethods.html – Mattherick 2013-05-10 10:11:28

相关问题