我有一个用户和一个文章模型。当我保存一篇文章时,我还需要保存哪个用户创建了这篇文章,因此我需要他的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感谢您的帮助!
发布于 2013-05-10 06:25:55
你应该在你的控制器中做这样的事情:
def create
@article = current_user.articles.build(params[:article])
...
end或
def create
@article = Article.new(params[:article].merge(:user_id => current_user.id))
...
end但我更喜欢第一个。
https://stackoverflow.com/questions/16471966
复制相似问题