2013-04-22 103 views
0

我有一个STI表(Vote),其中有许多子项(Tag::Vote,User::Vote,Group::Vote等)。所有的孩子类共享,看起来像这样一个非常类似的方法:Rails:获取父类方法中子类的类名称

def self.cast_vote(params) 
    value = params[:value] 
    vote = Tag::Vote.where(:user_id => User.current.id, 
    :voteable_type => params[:voteable_type], 
    :voteable_id => params[:voteable_id]).first_or_create(:value => value) 
    Vote.create_update_or_destroy_vote(vote, value) 
end 

从一类到下一个唯一的区别是在第二行,当我指的是孩子的班级名称:

vote = Tag::Vote.where. . . . 

我想重构这个方法到父类中。当我更换二线它几乎工程:

vote = self.where. . . . 

这里的问题是,selfVote,而不是Tag::VoteUser::Vote。反过来,type列(Rails自动填充子类名称)设置为零,因为它来自Vote而不是其中一个子项。

是否有一种方法让子类继承此方法并调用它自己,而不是它的父类?

回答

1

如果你想正确设置类型,我不认为你可以避免了解特定子类的知识,但是你可以简化代码,这样代码重复就少得多。例如:

class Vote 
    def self.cast_vote_of_type(params, subtype) 
    ....first_or_create(value: value, type: subtype) 
    end 
end 

class Tag::Vote 
    def self.cast_vote(params) 
    cast_vote_of_type(params, self.class.name) 
    end 
end 
+0

这是一个明显的改进。 – nullnullnull 2013-04-22 15:40:15

相关问题