1

많은 컨트롤러에 대해 일반적인 투표 컨트롤러를 만들고 싶습니다.thumbs_up 투표 보석의 다형성 클래스

저는 이전에 vote_fu 보석이었던 Thumbs_up 보석을 사용하고 있습니다. 그래서 객체 @voteable있는 부분 인처럼

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

나의 양식은 같습니다

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

을 그러나 내가 컨트롤러로 voteable 객체를 전달하려고 할 때 직접 작동하지 않습니다. 문자열에 대한

정의되지 않은 메서드`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 %>