1

さまざまなコントローラー用の汎用投票コントローラーを作成したいと思います。

以前はvote_fugemであったThumbs_upgemを使用しています。

https://github.com/kitop/thumbs_up/blob/master/lib/acts_as_voter.rb

私のフォームはそのように見えますが、これはオブジェクト@voteableの部分です:

<strong class="result">Votes: <%= voteable.votes_for - voteable.votes_against %></strong>

<%= form_tag user_votes_path(current_user) do |f| %>
    <%= radio_button_tag :thumb_direction, :up %>
    <%= radio_button_tag :thumb_direction, :down %>
    <%= hidden_field_tag :voteable, @voteable %>
    <%= submit_tag :vote %>
<% end %>

ただし、投票可能なオブジェクトをコントローラーに直接渡そうとすると、機能しません。

String:Classの未定義のメソッド `base_class'

私の質問は、同じオブジェクトを多形的に検索する方法です...つまり、オブジェクト自体の代わりにvoteable_typeと_idを渡します...他にもっと簡単な方法がない限り?

コントローラはこんな感じ

  def create
    #@user = User.find(params[:user_id])
    current_user.vote(params[:voteable], :direction => params[:thumb_direction], :exclusive => true)
  end

#routes

  resources :users do
    resources :votes
  end
4

1 に答える 1

3

このようなことをしました

  def create
    voteable_class = params[:voteable_type].constantize
    voteable_id = (params[:voteable_type].downcase + "_id").to_sym
    voteable_instance = voteable_class.find(params[voteable_id])
    current_user.vote(voteable_instance, :direction => params[:thumb_direction], :exclusive => true)
    redirect_to :back
  end

そして、使用したい各モデルのネストされた投票リソースのルートを変更しました。

erb

<%= form_tag [voteable, Vote.new] do |f| %>
    <%= radio_button_tag :thumb_direction, :up %>
    <%= radio_button_tag :thumb_direction, :down %>
    <%= hidden_field_tag :voteable_type, voteable.class %>
    <%= submit_tag :vote %>
<% end %>
于 2011-02-01T05:44:10.483 に答える