Ruby on rails 在Ruby中使用send()将对象传递给方法时出错
我在使用Ruby on rails 在Ruby中使用send()将对象传递给方法时出错,ruby-on-rails,ruby,metaprogramming,Ruby On Rails,Ruby,Metaprogramming,我在使用send()调用方法时遇到问题,同时将所述方法传递给对象。我收到WorkItemMailer:Class的未定义方法“employee\u feedback(#))错误 这在我的工作_item.rb模型中: def send_work_item_mail forms_needing_mail = ["employee", "install", "repair"] if forms_needing_mail.include?(self.form) WorkI
send()
调用方法时遇到问题,同时将所述方法传递给对象。我收到WorkItemMailer:Class的未定义方法“employee\u feedback(#))错误
这在我的工作_item.rb模型中:
def send_work_item_mail
forms_needing_mail = ["employee", "install", "repair"]
if forms_needing_mail.include?(self.form)
WorkItemMailer.send("#{self.form}_feedback(#{self})").deliver_now
end
end
被称为:
@work_item.send_work_item_mail
WorkItemMailer.send(:employee_feedback, self)
在我的工作中\u items\u controller.rb
以下是我的邮件中的方法:
def employee_feedback(work_item)
@work_item = work_item
@employee = User.find_by(id: @work_item.employee)
@manager = User.find_by(id: @employee.manager)
mail to: @manager.email, subject: "Employee feedback for #{@employee.name}"
end
我是否使用了错误的send,或者这里还有其他原因吗?试试这个
WorkItemMailer.send("#{self.form}_feedback".to_sym, self).deliver_now
对对象调用send
,与直接调用方法完全相同。不同之处在于将方法名称作为参数传递给send
。
要发送的后续参数(在方法名称之后)将作为方法中的参数传递
因此:
WorkItemMailer.employee_feedback(self)
应称为:
@work_item.send_work_item_mail
WorkItemMailer.send(:employee_feedback, self)
就你而言:
WorkItemMailer.send("#{self.form}_feedback", self).deliver_now
“`are typo or the present in the exception?”,如果不是打字错误,这就是问题所在。typo。在将其粘贴到我的解释中时添加了它,因为`正在阻止代码格式正常工作。应删除元编程标记<代码>发送
是最基本的。@CarySwoveland:好吧,不是超基本的。但是,是的,与“meta”相去甚远。@Sergio,我一直认为puts“It's Good day”
是send(:puts,“It's Good day.”)的语法糖。
(用于公共方法)。谢谢。不幸的是,仍然收到相同的错误。如果您运行WorkItemMailer.send(“employee_feedback(#{WorkItem.first})”).deliver_现在从控制台收到错误?确实-NoMethodError:WorkItemMailer的未定义方法“`employee_feedback(WorkItem.first)”:Class
看起来问题出在send()
寻找整个字符串作为方法,而不是将对象作为参数传递-它将对象ID作为字符串传递作为方法调用的一部分。哎呀,我打错了(忘记了#{}),但我从ConsoleUnderful收到了与以前相同的错误,谢谢。效果很好。不过,不需要将其作为数组传递-只需self
就可以了。数组怎么了?