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

时间:2013-03-26 00:33:22

标签: ruby-on-rails ruby

我想通过制作一个可以重用的常用方法来干掉我的Rails代码。为了做到这一点,我必须创建一些字段/属性和代码变量中使用的类名,因此它可以用于具有相同代码的三个模型(及其字段)。我试图从这个questionthis one中学习,但我无法让它发挥作用。

在我的模型中,我有这个:

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

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

2 个答案:

答案 0 :(得分:2)

如果要分配属性,则需要使用等号的方法名称:

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

另外,这个:

rank_class = (klass.name).constantize

相当于:

rank_class = klass

答案 1 :(得分:1)

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

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

<强>顺便说一句

这是您原始问题的answer