出于测试/学习目的,我有一个具有以下属性的测验模型(来自 schema.rb 的片段):
create_table "quizzes", force: true do |t|
t.integer "user_id"
t.string "answer1"
t.string "answer2"
t.string "answer3"
t.string "answer4"
t.string "answer5"
t.string "answer6"
t.string "answer7"
t.string "answer8"
t.datetime "created_at"
t.datetime "updated_at"
end
add_index "quizzes", ["user_id"], name: "index_quizzes_on_user_id"
测验被发送到"new" View ,如下所示:
def new
@quiz = Quiz.new(user_id: current_user.id)
end
当用户完成测验时,会触发 QuizzesController#create 操作:
def create
@results = Quiz.create(post_params) #from private method
render :show
end
(无论这呈现“显示” View 还是默认的“创建” View ,它都有效 - 在我测试和学习时,我现在将这两个 View 作为占位符)
post_params 方法如下所示:
def post_params
params.require(:quiz).permit(:user_id, :answer1, :answer2, :answer3, :answer4, :answer5, :answer6, :answer7, :answer8) #add other attributes here
end
(我也尝试过 params.require(:quiz).permit!
但我得到了相同的结果)。
问题是,在 View 中,它看起来像这样:
<div class="container">
<!-- Example row of columns -->
<div class="row">
<h1>Results</h1>
<p><%= @results.inspect %></p>
</div>
</div>
...@results.inspect 行显示所有 answer1、answer2 等属性,但将 user_id 属性显示为 nil - 尽管在 QuizzessController#new 操作中使用 user_id 设置了测验。我做错了什么,导致 user_id 无法正确传递?
最佳答案
如果您始终要将 user_id
设置为 current_user.id
,我建议您在 create
操作中添加该属性.
这样您就不必担心用户输入。否则,用户可能会滥用此更改 ID,从而将测验添加到另一个用户。
首先,从允许的 post_params 中删除 user_id
def post_params
params.require(:quiz).permit(:answer1, :answer2, :answer3, :answer4, :answer5, :answer6, :answer7, :answer8)
end
然后只需将您的创建操作更新为:
def create
# as mentioned by tagCindy, this is the way to set up the association
@quiz = current_user.build_quiz(post_params)
# you should also re-render the new form if there are any errors
if @quiz.save
render :show
else
render :new
end
end
关于ruby-on-rails - Rails : most Quiz attributes passing to params, 除了 user_id 之外。为什么?,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/27507697/