1

多くの異なるコントローラー用の一般的な投票コントローラーを作りたいと思います。thumbs_up投票宝石のポリモーフクラス

私は以前はvote_fu宝石だったThumbs_up宝石を使用しています。

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

私のフォームは、オブジェクト@voteableと部分的であるので、次のようになります。私はコントローラに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 %> 

。 文字列のための

未定義のメソッド `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 

答えて

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 %>