我正在实现一个方法,它将在项目的许多地方使用。
def do association
end“关联”是一个符号,像:articles,:tags,:users等。
当关联为:articles时,我需要使用文章模型。
当关联为:users时,我需要使用用户模型。
等。
我知道,我可以编写一个助手方法,根据提供的符号返回模型类。但是有没有现成的方法来解决这个问题呢?
发布于 2011-03-16 04:47:56
为此,Rails在String类上提供了一个名为classify的方法。
:users.to_s.classify.constantize
#User
:line_items.to_s.classify.constantize
#LineItem编辑:
如果您正在尝试检索与关联相关联的类,请使用以下方法:
Author.reflect_on_association(:books).klass
# => Book这将解决关联名称与类名称不匹配的情况。
例如:
class Order
has_many :line_items
has_many :active_line_items, :class_name => "LineItem",
:conditions => {:deleted => false}
end在上面的示例中,:active_line_items将导致ActiveLineItem,并且我们的原始代码将抛出错误。
阅读有关此here的更多信息。
发布于 2011-03-16 02:34:32
这将会起作用
(:users.to_s.singularize.capitalize.constantize).find :all, :conditions => ["name = ?", "john"]在你的例子中
association.to_s.singularize.capitalize.constantizehttps://stackoverflow.com/questions/5316290
复制相似问题