我正在通过生成一个小表单render_to_string
,由于某种原因,CSRF 令牌没有正确生成(即它与标题不同,用户在提交时注销,以及日志上的“无法验证 CSRF 令牌” )。以下是相关代码:
控制器:
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"
这工作得很好,无需附加到页面,而是在布局中呈现。请注意,这不是远程表单。