gpt4 book ai didi

ruby-on-rails-3 - 设计 rails 将 user_id 添加到另一个模型

转载 作者:行者123 更新时间:2023-12-01 04:37:13 25 4
gpt4 key购买 nike

我想将 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

在我的问题 Controller 中:

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 不会记录在我的数据库中吗?

最佳答案

试试这个:

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

关于ruby-on-rails-3 - 设计 rails 将 user_id 添加到另一个模型,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/6693152/

25 4 0
Copyright 2021 - 2024 cfsdn All Rights Reserved 蜀ICP备2022000587号
广告合作:1813099741@qq.com 6ren.com