我正在通过 render_to_string
生成一个小表格并且由于某种原因,CSRF token 没有正确生成(即它与 header 不同,用户在提交时注销,以及日志上的“无法验证 CSRF token ”)。这是相关的代码:
Controller :
def publish
@question = @event.questions.find(params[:id])
@question.update_attribute(:published, true) unless @question.published?
Pusher[@event.to_param].trigger('new_question', question: render_question)
redirect_to event_path(@event)
end
private
def render_question
render_to_string('questions/_unanswered_question', locals: {question: @question}, layout: false)
end
def fetch_event
@event ||= current_user.events.find(params[:event_id])
end
我正在使用 Pusher,但您可以假设这只是使用此 Javascript 呈现在页面上:
$("#questions").append(data.question); // data is what I send from Pusher.
最后,正在渲染的部分:
.answer
= form_for [@event, question, question.answers.new] do |f|
%h2
= question.title
%ul
- (1..5).each do |n|
- if question.send("answer_#{n}").present?
%li
= f.radio_button :option, n, id: "q_#{question.id}_answer_option_#{n}"
= f.label question.send("answer_#{n}"), for: "q_#{question.id}_answer_option_#{n}"
%p
= f.submit "Answer"
这在没有附加到页面的情况下工作得很好,但在布局中呈现。请注意,这不是远程表单。
最佳答案
看起来您正在使用 ajax 生成表单,然后将其添加到 Dom。为每个请求生成新的 csrf token 。据我所知,您必须使用 header 中可用的 csrf token ,并使用 js 将表单中的 token 替换为它。
应该是这样的:
success: ()->
parameter = $("meta[name=csrf-param]").attr("content")
token = $("meta[name=csrf-token]").attr("content")
question = $(data.question).find("[name="+parameter+"]").val(token)
目前我没有电脑可以先测试,所以希望我是对的:/
关于ruby-on-rails - 使用 render_to_string 时创建的真实性 token 不同,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/17953105/