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

标签 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

我的文章_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 呢?我想要一个有 session 的人!我在 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

感谢您的帮助!

最佳答案

你应该在你的 Controller 中做这样的事情:

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

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

但我更喜欢第一个。

关于ruby-on-rails - rails 3 : Get current user_id to save in different model,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/16471966/

相关文章:

ruby - ruby 中的实例变量

ruby-on-rails - 每个用户的 Rails carrierwave 上传目录

ruby-on-rails - 在 Rails 中访问只读数据库的最佳方式

ruby-on-rails - 在rails form_for方法中设置参数值

ruby-on-rails - rails 集成测试通过 Itest 但 "rake test:integration"未提供任何输出。虽然没有错误

ruby-on-rails - 邪恶的 PDF 无法处理分页符

javascript - 如何防止 jQuery onclick 事件中的 Ruby 方法在页面刷新时执行

html - 如何使我的索引页面上的帖子出于样式目的分离元素?

ruby - 这个方法在ruby中如何使用自己的方法呢?

ruby - 各种正则表达式选项