2

ページをリロードせずに、Rails モデルのデータを更新する必要があります (AJAX)。

http://railscasts.com/episodes/364-active-record-reputation-system?autoplay=trueのような評判システムがあります

私のコントローラーには、次のメソッドがあります。

def vote
   value = params[:type] == "up" ? 1 : -1
   @idea = Idea.find(params[:id])
   @idea.add_or_update_evaluation(:votes, value, current_user)
   redirect_to :back, notice: "Thank you for voting!"

end

私の見解では、これがあります:

<% if current_user && !current_user.voted_for?(idea) %>
| <%= link_to "LoV", vote_idea_path(idea, type: "up"), method: "post" %>
<% end %>

ページをリロードせずに次のデータを更新したいと思います。私のアプリケーション レイアウト ファイルには次のようなものがあります。

strong>(<%= current_user.reputation_value_for(:votes).to_i %>).</strong>
<strong>LoV's(<%= link_to current_user.evaluations.count, user_path(current_user)%>)</strong>

そのメソッド「投票」をAJAXでレンダリングするにはどうすればよいですか?

どうもありがとう。

4

1 に答える 1

-2

簡単な JavaScript をセットアップします。

投票-ajax.js.coffee

$("a.vote").on
    click: (event) ->
        link = $(event.target)
        $.ajax
            type:     "POST"
            url:      "/votes"
            dataType: "json"
            data:
                voteType: link.attr("data-type")
                userId:   link.attr("data-userId")

            success: (response) ->
                link.addClass("voted-#{link.attr("data-type")}")

         event.preventDefault()
         false

votes_controller.rb

respond_to :json

def create
  @vote = Vote.new(direction: params[:voteType], user_id: params[:userId])
  @vote.save
  respond_with @vote
end

これは完全な例ではなく、テストもされていません。微調整を行う必要がありますが、正しい道を歩み始めることができます。

使用することもできます

<%= link_to "Vote Up", votes_path(direction: "up"), method: :post, remote: true %>

create.js.erb応答を処理するには、フォルダー内にファイルを作成する必要があります。これは、基本的に上記のメソッドviews/votesのコールバックのように見えるはずです。success

個人的には、手動の方法 (jQuery の を使用ajax) の方が制御性が高く、近い将来に変更される可能性が低いため、(jQuery の を使用して) 好みますが、Rails の UJS 実装は変更される可能性が高くなります。また、単純な coffeescript を書くための変更も提供します。これは常におまけです!

于 2012-10-03T03:58:21.573 に答える