답변:
이렇게하면됩니다.
class HouseBuyersController < ApplicationController
def index
@model_name = controller_name.classify
end
end
이것은 종종 컨트롤러 작업을 추상화 할 때 필요합니다.
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
controller_name.sub('_', ' ').titleize"House Buyers"를 얻기 위해 할 수 있습니다 .
new.controller_name.classify.constantize클래스 정의에서 사용할 수 있습니다 .
약간의 해킹이지만 모델 이름이 컨트롤러 이름을 따서 명명 된 경우 :
class HouseBuyersController < ApplicationController
def my_method
@model_name = self.class.name.sub("Controller", "").singularize
end
end
... @model_name 인스턴스 변수에 "HouseBuyer"를 제공합니다.
다시 말하지만, 이것은 "HouseBuyersController"가 "HouseBuyer"모델만을 다룬다는 거대한 가정을 만듭니다.
코드가 따르지 않는 것처럼 보이는 기본 MVC를 사용하는 경우에는 불가능합니다. 컨트롤러가 모델 인 것 같지만 유형이있을 수 있습니다. 어쨌든 컨트롤러와 모델은 Rails MVC에서 근본적으로 분리되어 있으므로 컨트롤러는 연결된 모델을 알 수 없습니다.
예를 들어 post라는 모델이있을 수 있습니다. 여기에는 posts_controller 컨트롤러가 있거나 article_controller와 같은 컨트롤러가있을 수 있습니다. Rails는 컨트롤러에서 다음과 같은 실제 코드를 정의 할 때만 모델에 대해 알고 있습니다.
def index
@posts = Post.all
@posts = Article.all
end
Rails 표준 컨트롤러에서는 모델이 무엇인지 알 수있는 방법이 없습니다.