Object.send( “#{字段}<<”,值)

时间:2014-01-31 11:54:59

标签: ruby-on-rails ruby

这很有效。

profile.educations << education_model

但这不是

profile.send("#{model_name.underscore.pluralize}<<", model_model)

,其中

model_name = "Education"
model_model = model_name.constantize.new

并给我以下错误

undefined method `Educations<<' for #<Profile:0x007f20dc1089a8>

1 个答案:

答案 0 :(得分:5)

您的方法不起作用,因为educations<<是单独的方法,无法像您尝试的那样链接。由于您不需要动态获取<<方法名称,因此您可以定期调用它,而无需使用send。此外,您应该在underscore上调用model_name,因为rails约定是强调关联名称(更常见的是方法名称)。所以以下内容应该有效:

profile.send("#{model_name.underscore.pluralize}") << model_model