2013-07-30 55 views
4

我通过render_to_string生成一个小表单,出于某种原因,CSRF令牌没有正确生成(即,它与头部不同,并且用户在提交时注销) a“日志中无法验证CSRF令牌”)。下面是相关的代码:使用render_to_string创建真实性令牌

控制器:

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 

我使用推,但是你可以认为这只是所呈现的页面上有此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" 

这工作得很好,没有被附加到pa ge,但在布局中呈现。请注意,这不是一个远程表单。

+0

你可以发表你的'application.html.erb'文件代码请?需要头部'这部分 ......'或者你能告诉我crf_token标签是否存在? – rmagnum2002

+0

'csrf_meta_tags'存在。 –

+1

您可以发布将用户注销的请求参数吗?您可以在请求后立即在日志文件中找到发送的参数。 –

回答

0

看起来你正在使用ajax生成表单然后将其添加到Dom。为每个请求生成新的csrf标记。据我所知,你必须使用头部可用的csrf标记,并用js替换表单中的标记。

应该是这个样子:

success:()-> 
    parameter = $("meta[name=csrf-param]").attr("content") 
    token  = $("meta[name=csrf-token]").attr("content") 
    question = $(data.question).find("[name="+parameter+"]").val(token) 

目前我有没有电脑先测试,所以希望我是对的:/

相关问题