我想将设计中的current_user.id添加到另一个模型......
问题模型:
class Question < ActiveRecord::Base
belongs_to :user
attr_accessible :content
validates :content, :presence => true
end
用户模型:
class User < ActiveRecord::Base
has_many :questions
# Include default devise modules. Others available are:
# :token_authenticatable, :encryptable, :confirmable, :lockable, :timeoutable and :omniauthable
devise :database_authenticatable, :registerable,
:recoverable, :rememberable, :trackable, :validatable
# Setup accessible (or protected) attributes for your model
attr_accessible :email, :password, :password_confirmation, :remember_me
end
我的问题迁移:
class CreateQuestions < ActiveRecord::Migration
def change
create_table :questions do |t|
t.string :content
t.date :deadline
t.integer :user_id
t.timestamps
end
end
end
在我的问题控制器中:
def create
params[:question][:user_id]=current_user.id
@question = Question.new(params[:question])
if @question.save
redirect_to questions_path, :notice => "Successfully created question."
else
setup_questions
render :index
end
end
当我保存问题时,current_user.id将不会记录在我的数据库中?
答案 0 :(得分:8)
请改为尝试:
def create
@question = Question.new(params[:question])
@question.user_id = current_user.id
if @question.save
redirect_to questions_path, :notice => "Successfully created question."
else
setup_questions
render :index
end
end