通过包含字段名称的字符串变量引用模型字段?(Refer to model field by string variable that contains the name of the field?)

编程入门 行业动态 更新时间:2024-10-24 01:49:18
通过包含字段名称的字符串变量引用模型字段?(Refer to model field by string variable that contains the name of the field?)

我无法弄清楚如何用谷歌搜索这个词 - 请原谅。 如果我有一个像这样的模型:

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.all

I could say:

c.Color[0].color_name

So 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].b

Or, 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)

更多推荐

本文发布于:2023-08-01 20:33:00,感谢您对本站的认可!
本文链接:https://www.elefans.com/category/jswz/34/1363763.html
版权声明:本站内容均来自互联网,仅供演示用,请勿用于商业和其他非法用途。如果侵犯了您的权益请与我们联系,我们将在24小时内删除。
本文标签:字段   字符串   变量   模型   名称

发布评论

评论列表 (有 0 条评论)
草根站长

>www.elefans.com

编程频道|电子爱好者 - 技术资讯及电子产品介绍!