在Rails中使用变量名称作为属性

在Rails中使用变量名称作为属性

问题描述:

我想通过制作一个可重用的常用方法来干掉我的Rails代码。为此,我必须创建一些字段/属性以及代码变量中使用的类名称,以便它可以为三个模型(及其字段)使用相同的代码。我试图从这个questionthis one中学习,但我一直无法使它工作。在Rails中使用变量名称作为属性

在我的模型,我有这样的:

def self.update_percentages  
    update_percentages_2(User, "rank", "top_percent") 
end 

def self.update_percentages_2(klass, rank_field, percent_field) 
    rank_class = (klass.name).constantize 
    total_ranks = rank_class.maximum(rank_field) 
    top_5 = (total_ranks * 0.05).ceil 

    rank_class.find_each do |f| 
    if f.send("#{rank_field}") <= top_5 
     f.send("#{percent_field}", 5) 
     f.save 
    end 
    end 
end 

有了这个代码,我得到ArgumentError: wrong number of arguments (1 for 0)。当我开始发表评论以缩小问题范围时,看起来f.send("#{percent_field}", 5)会导致错误。

如果我补充一下: percent_field = (percent_field).constantize

我得到:Name Error: wrong constant name top_percent

有人可以帮我确定我做错了什么吗?

如果你想分配给一个属性,你需要的方法名等号:

f.send("#{percent_field}=", 5) 

而且,这样的:

rank_class = (klass.name).constantize 

是相同的:

rank_class = klass 

我会重写您的方法来更新交易中的所有合格记录。

def self.update_percentages_2(klass, rank_field, percent_field) 
    top_5 = (klass.maximum(rank_field) * 0.05).ceil 
    klass.where("#{rank_field} <= ?", top_5).update_all(percent_field => 5) 
end 

BTW

这里是一个answer到你原来的问题。