2013-04-22 82 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