在我的應用程序中,我有資源問題和用戶,我必須給用戶提供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或建議
Upvoted爲HAML :) –