2016-07-29 30 views
2

在我的應用程序中,我有資源問題和用戶,我必須給用戶提供upvote或downvote問題的機會。我通過對用戶和問題的投票建立了關係has_many。我也設置投票。我是網絡開發中的一個紐約人,所以我就是這樣設置的,像這樣:在Rails應用程序中需要一些幫助來渲染JSON

-if current_user.votes_on_questions.include? @question 
    -if @question.votes.where(user_id: current_user.id).first.vote_field == true 
    = form_for @question.votes.where(user_id: current_user.id).first, method: :patch do |f| 
     = f.hidden_field :user_id, value: current_user.id 
     = f.hidden_field :votable_id, value: @question.id 
     = f.hidden_field :votable_type, value: 'Question' 
     = f.hidden_field :vote_field, value: false 
     = f.submit 'Vote +', class: 'upvote-submit' 
    -elsif @question.votes.where(user_id: current_user.id).first.vote_field == false 
    = form_for @question.votes.where(user_id: current_user.id).first, method: :patch do |f| 
     = f.hidden_field :user_id, value: current_user.id 
     = f.hidden_field :votable_id, value: @question.id 
     = f.hidden_field :votable_type, value: 'Question' 
     = f.hidden_field :vote_field, value: true 
     = f.submit 'Vote -', class: 'upvote-submit' 
-else 
    div.voting_dom 
    = render 'votes/vote', question: @question 

看起來很可怕哈?別忘了 - 我是一個完整的nuber。 簡單的JS

$(document).ready(function(){ 
    $('.new_vote').bind("ajax:success", function(e, data, stauts, xhr){  
    $('.voting_dom').replaceWith(xhr.responseText); 
    }); 
}); 

和控制器

def create 
    @vote = Vote.new(vote_params) 
    respond_to do |format| 
    if @vote.save 
    format.json{ render json: @vote } 
    else 
    format.json{ render json: @vote.errors.full_messages, status: :unprocessable_entity } 
    end 
end 

末開始

我堅持就如何如何設置JSON響應。將非常感謝任何commet或建議

+0

Upvoted爲HAML :) –

回答

0

因爲你只是想呈現JSON,我會放棄使用respond_to

嘗試類似:

if @vote.save 
render json: @vote 
else 
    render json: @vote.errors.full_messages, status: :unprocessable_entity 
end 
+0

好吧!我現在的問題是,我必須使用接收的@vote來渲染表單。我怎樣才能做到這一點? –

+0

我不確定我明白你在問什麼?你的意思是你想要改變基於Ajax響應的頁面嗎?你想用這個表格做什麼? –

+0

)))在我的情況下,vote partial是一種形式。我不是那麼好的英語發言者,對此感到遺憾。我有3個選項第一個 - 用戶還沒有投票,所以應該有一個2表單(一個用於upvote另一個downvote)與網址投票#創建。它應該與json做出反應,用ajaj來回應(對我來說),但任務是發回json。所以現在頁面應該只呈現一個表單,它應該有url來投票#更新。我自己做了一些嘗試,但我在這裏是一個新手,你能告訴我應該在哪裏發佈給你看。更新我的頭文章? –