Ruby send(attribute.to_sym) for Rails Method



我使用Ruby 1.9.2,需要遍历表的所有值,以确保所有值都是UTF-8编码。有很多列,所以我希望能够使用column_names方法遍历它们并将值编码为UTF-8。我想这可能有用:

def self.make_utf
  for listing in Listing.all
    for column in Listing.column_names
      column_value_utf = listing.send(column.to_sym).encode('UTF-8')
      listing.send(column.to_sym) = column_value_utf
    end
    listing.save
  end
  return "Updated columns to UTF-8"
end

但是它返回一个错误:

syntax error, unexpected '=', expecting keyword_end
        listing.send(column.to_sym) = column_value_utf

我不知道如何使这个正常工作。

您使用了错误的send,并且您正在发送错误的符号来执行您想要执行的操作:

listing.send(column + '=', column_value_utf)

你试图用column_value_utf作为参数调用x=方法(对于某些x),这就是o.x = column_value_utf通常会做的。因此,您需要构建正确的方法名称(只需一个字符串即可),然后将该方法的参数作为参数发送给send

最新更新