我无法弄清楚如何用谷歌搜索这个词 - 请原谅。 如果我有一个像这样的模型:
c = Color.all我可以说:
c.Color[0].color_name因此,如果我有一个包含该模型中字段名称的变量,如:
b = 'color_name'我怎么能这样说(“c.color_name”)使用带有字段名称的字符串:
c[0].b或者,我的意思是告诉Ruby / Rails使用vaiable的内容作为字段名称:
c[0].[the string value of b]我已经摸索着尝试我能想到的一切,但是我无法弄清楚这个的语法。
谢谢!
Rails 2.3.5 / Ruby 1.8.7
I can't figure out how to word this for a google search - pardon. If I have a model like:
c = Color.allI could say:
c.Color[0].color_nameSo if I then have a variable that contains the name of a field in that model like:
b = 'color_name'How could I say ("c.color_name") like this using the string with the field name:
c[0].bOr, I mean tell Ruby/Rails to use the contents of the vaiable as the field name:
c[0].[the string value of b]I've fumbled around trying everything I can think of but the syntax for this I can't figure out.
Thanks!
Rails 2.3.5 / Ruby 1.8.7
最满意答案
如果b是Color的实例变量或方法,请使用Object的send方法
c = Color.all b = 'color_name' c[0].send(b.to_sym)If b is an instance variable or method of a Color, use the send method from Object
c = Color.all b = 'color_name' c[0].send(b.to_sym)更多推荐
发布评论