2013-07-30 35 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) 

目前我有沒有電腦先測試,所以希望我是對的:/

相關問題