Rails 5.2
我有一个目录模型,具有以下方法:
def current_items
....
end
def sales_items
....
end
有十几种方法,我想在我的助手中定义一个数组
categories = ['current', 'sales', ....]
categories.each do |category|
m = "{category}_items"
@items = Catalog.m
...
end
但是,我收到一个错误:
undefined method 'm' for Catalog:Class
知道这是否可以做到吗?
请尝试以下代码:-
class Catalog < ActiveRecord::Base
def self.current_items
puts "from current_items"
end
def self.sales_items
puts "from sales_items"
end
end
然后致电:-
如果公开
m = "#{category}_items" @items = Catalog.public_send(m)
如果是私有的
m = "#{category}_items" @items = Catalog.send(m)
谢谢:)
尝试public_send
调用类中的公共方法,如果您也想调用私有方法,请使用send
,但如果不需要,请避免使用send
m = "#{category}_items"
Catalog.public_send(m)
试一试!