我试图根据包含对象名称的字符串访问对象。该对象是作用域的(我使用cancan来确保用户只能访问允许访问的记录)。我已经包含在其中,我有以下一些代码:Rails从包含对象名称的字符串访问对象
operation_type:string, one of %w(add sub mult div)
left_operand_object:string
left_operand:string
right_operand_object:string
right_operand:string
def result
r = [access object using left_operand_object]
k = [access object using right_operand_object]
if operation_type == 'add'
r.instance_variable_get('@'+left_operand) + k.instance_variable_get('@'+left_operand)
elsif operation_type == 'sub'
r.instance_variable_get('@'+left_operand) - k.instance_variable_get('@'+left_operand)
...
end
于是,两个问题:
- 我怎样才能完成
r = [access object using left_operand_object]
线,让我根据访问范围的对象的姓名字符串left_operand_object
? - 将
instance_variable_get
工作,如果left_operand
是customers.count
或者它只会工作没有计数方法?
任何帮助非常感谢!
是的,你理解正确 - left_operand_object会像“客户”。感谢您的信息,我会考虑使用constantize - 我认为这将分配对象到r变量,如预期的那样? –
我认为第二个问题有点不清楚 - 我问我是否可以使用instance_variable_get中的count方法作为整数返回count,但我认为你的答案给了我需要去的方向 - left_operand会是像“sales.count”(假设我试图使用customer.sales.count)。 –
我编辑了我的答案以允许“sales.count” –