Two or more controllers sharing same voting action (just the model class differing) - how to create a mixin to be included in all controllers?
I'm new to rails and I'm trying to create some generic code and reuse it across several controllers. Basically I'm using the thumbs_up gem which allows some models to act as voteable and other models to act as voter (user model, for instance).
Imagine the following scenario:
I have the Question and Answer models. Question has many answers. Both question and answer are voteable.
Routes.rb:
resources :questions do
    resources :answers do
      member do
        get 'vote_up'
        get 'vote_down'
      end
    end
    member do
      get 'vote_up'
      get 'vote_down'
    end
  end
I've implemented a solution where each of my voteable models hav开发者_StackOverflow社区e their own controllers where the vote_up and vote_down actions are processed. However, in both controllers these actions are basically the same, the only difference being the model class used to find the instance to be voted on. Example:
QuestionsContoller:
  def vote_up
    @voteable = Question.find(params[:id])
    current_user.vote_exclusively_for(@voteable)  
    respond_to do |format|
      format.js { render :action => 'votes/vote_completed' }
    end
  end
AnswersContoller:
  def vote_up
    @voteable = Answer.find(params[:id])
    current_user.vote_exclusively_for(@voteable)  
    respond_to do |format|
      format.js { render :action => 'votes/vote_completed' }
    end
  end
I would like to create a mixin with this code to be included in both controllers, can anyone shed some light on how to implement it? Should the mixin define the vote_up and vote_down methods? Or instead, should the mixin implement some auxiliary method which then is called in the vote_up and vote_down methods of each controller?
Is this the best approach for this problem or should there only be one single controller to handle the vote_up and vote_down actions?
I would very much appreciate your help on these matters. Many thanks in advance
Bruno
I'd rather go the polymorphic way but for your mixin (module) a solution can be this:
Questions Controller
include Voting
Voting Module:
module Voting
  def vote_up
    @voteable = Object.const_get(self.class.to_s.chomp('Controller').singularize).find(params[:id])
    current_user.vote_exclusively_for(@voteable)  
    respond_to do |format|
      format.js { render :action => 'votes/vote_completed' }
    end
  end
end
 
         加载中,请稍侯......
 加载中,请稍侯......
      
精彩评论