Rails 3:获取当前user_id以保存在不同的模型中

时间:2013-05-09 22:10:07

标签: ruby-on-rails ruby

我有一个用户和一个文章模型。 当我保存文章时,我还需要保存哪个用户创建了文章,因此我需要他的ID。所以我需要知道哪个用户创建了它?

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

感谢您的帮助!

1 个答案:

答案 0 :(得分: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

但我更喜欢第一个。