简体   繁体   English

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

[英]Rails 3: Get current user_id to save in different model

I have a user and a article model. 我有一个用户和一个文章模型。 When I save an article I also need to save which user created the article therefore I need his ID. 当我保存文章时,我还需要保存哪个用户创建了文章,因此我需要他的ID。 So I need to know which user created it? 所以我需要知道哪个用户创建了它?

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

My Article _form 我的文章_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 to i set the user_id in the article model correctly? 那么如何正确设置文章模型中的user_id? I would like the one who has a session! 我想要一个有会话的人! I have a helper_method in the application_controller But i am not sure how to use it. 我在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

Thanks for help! 感谢帮助!

You should do something like this in your 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 i would prefer the first one. 但我更喜欢第一个。

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM