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

pat*_*gan 0 ruby ruby-on-rails

这有效.

profile.educations << education_model
Run Code Online (Sandbox Code Playgroud)

但事实并非如此

profile.send("#{model_name.underscore.pluralize}<<", model_model)
Run Code Online (Sandbox Code Playgroud)

哪里

model_name = "Education"
model_model = model_name.constantize.new
Run Code Online (Sandbox Code Playgroud)

并给我以下错误

undefined method `Educations<<' for #<Profile:0x007f20dc1089a8>
Run Code Online (Sandbox Code Playgroud)

Mar*_*pka 5

你的方法不起作用,因为educations<<是单独的方法,不能像你尝试的那样链接.由于您不需要<<动态获取方法名称,因此可以以常规方式调用它,而无需使用send.此外,您应该调用underscore您的model_name,因为rails约定是强调关联名称(更一般地说 - 方法名称).所以以下应该有效:

profile.send("#{model_name.underscore.pluralize}") << model_model
Run Code Online (Sandbox Code Playgroud)