开发者

Rails - select object attribute based on user input

How would I select a specific attribute based on user input?

For example, say I have the following Object table, with attributes 'name', 'shape', 'color'. I'm trying to be able to select an attribute based on user input. If the user enters '1', for example, it should return开发者_开发百科 the value of the first attribute, 'name'.

Is there a way to do this without hard coding all the options with if statements like in the following? I have 28 attributes for my object, so doing all these if statements seems excessive.

if userInput == '1'
return @object.name
end


I have to think that this is not a good way to achieve your actual objective, but to answer the question you asked:

return @object.send @object.attribute_names[userInput.to_i]

Or perhaps:

@object.send %w{fieldname anotherfield yetanotherfieldname}[userInput.to_i]

Or perhaps:

@object.attributes.values[userInput.to_i]
0

上一篇:

下一篇:

精彩评论

暂无评论...
验证码 换一张
取 消

最新问答

问答排行榜