2

私はacts_as_votablegemをインストールしましたが、コンソールで正常に動作します(ドキュメントに記載されているように)。だから私の質問は、賛成と反対のボタンのフォームを設定する方法ですか?それとも単にリンクにすることができますか?

ドキュメントは次のとおりです:github.com/ryanto/acts_as_votable/blob/master/README.markdown

ユーザーと画像モデルがあります。ユーザーは写真を気に入ってくれるはずです。画像ビューからのコード。ボタンは次のようになります。

<% for picture in @pictures %> 
<p> 
<%= image_tag picture.image_url(:thumb).to_s %> 
</p> 
<%= picture.created_at.strftime("%a, %d %b. %Y") %>, by 
<%= link_to picture.user.name, picture.user %> 
<h2> <%= link_to picture.name, picture %></h2> 

[buttons here] 

<%= picture.votes.size %> <% end %>
4

2 に答える 2

9

これを行う1つの方法は、賛成票と反対票に対して独自のコントローラーアクションを追加することです。コントローラで使用可能なメソッドがあると想定していcurrent_userます。

# pictures_controller.rb
def upvote
  @picture = Picture.find(params[:id])
  @picture.liked_by current_user
  redirect_to @picture
end

def downvote
  @picture = Picture.find(params[:id])
  @picture.downvote_from current_user
  redirect_to @picture
end

# config/routes.rb

resources :pictures do
  member do
    put "like", to: "pictures#upvote"
    put "dislike", to: "pictures#downvote"
  end
end

# some view

<%= link_to "Upvote", like_picture_path(@picture), method: :put %>
<%= link_to "Downvote", dislike_picture_path(@picture), method: :put %>
于 2013-02-22T15:36:55.500 に答える
5

これが私がacts_as_commentablegemでもそれをやった方法です。ですから、これはあなたがコメントしているどんなオブジェクトでもうまくいくはずだと思います。

私の_comment.html.erbビューで

<%= link_to "Upvote", {:controller =>"comments", :action => "upvote", :id => comment.id}, :class => 'btn', method: :put %>
<%= link_to "Downvote", {:controller =>"comments", :action => "downvote", :id => comment.id}, :class => 'btn', method: :put %>

私のroutes.rbファイルで

put '/comments/:id/:action' => 'comments#upvote'
put '/comments/:id/:action' => 'comments#downvote'

それから私のコメントコントローラーで

class CommentsController < ApplicationController
  before_filter :load_commentable
  before_filter :find_comment, :only => [:upvote, :downvote]



  def upvote
    current_user.upvotes @comment
    redirect_to(@comment.commentable)
  end

  def downvote
    @comment.downvote_from current_user
    redirect_to(@comment.commentable)
  end




private

  def load_commentable
    resource, id = request.path.split('/')[1, 2]
    @commentable = resource.singularize.classify.constantize.find(id)
  end

  def find_comment
    @comment = Comment.find(@commentable.id)
  end


end

beforeフィルターはより多様性を可能にするので、これをコメント可能なオブジェクトに追加できます。私はたまたまお祭りでしたが、写真など何でもできました。詳細については、acts_as_commentableのドキュメントとpolymorphicrailscastを確認してください。これは私の最初の投稿なので、これがひどいコードである場合は、教えてください。

于 2013-02-27T00:19:36.373 に答える