本文介绍了Rails:如何根据控制器类名获取模型类名?的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

class HouseBuyersController < ...
  def my_method
    # How could I get here the relevant model name, i.e. "HouseBuyer" ?
  end
end

推荐答案

这样做:

class HouseBuyersController < ApplicationController

  def index
    @model_name = controller_name.classify
  end

end

这在抽象控制器动作时经常需要:

This is often needed when abstracting controller actions:

class HouseBuyersController < ApplicationController

  def index
    # Equivalent of @house_buyers = HouseBuyer.find(:all)
    objects = controller_name.classify.constantize.find(:all)
    instance_variable_set("@#{controller_name}", objects)
  end

end

这篇关于Rails:如何根据控制器类名获取模型类名?的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持!

08-03 19:21