반응형
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
이것은 종종 컨트롤러 작업을 추상화 할 때 필요합니다.
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_path.classify
controller_path
네임 스페이스를 제공합니다. controller_name
하지 않습니다.
예를 들어 컨트롤러가
Admin::RolesController
그때:
controller_path.classify # "Admin::Role" # CORRECT
controller_name.classify # "Role" # INCORRECT
약간의 해킹이지만 모델 이름이 컨트롤러 이름을 따서 명명 된 경우 :
class HouseBuyersController < ApplicationController
def my_method
@model_name = self.class.name.sub("Controller", "").singularize
end
end
... @model_name 인스턴스 변수에 "HouseBuyer"를 제공합니다.
다시 말하지만, 이것은 "HouseBuyersController"가 "HouseBuyer"모델만을 다룬다는 거대한 가정을 만듭니다.
작동하는 네임 스페이스의 경우 :
def resource_class
controller_path.classify.constantize
end
코드가 따르지 않는 것처럼 보이는 기본 MVC를 사용하는 경우에는 불가능합니다. 컨트롤러가 모델 인 것 같지만 유형이있을 수 있습니다. 어쨌든 컨트롤러와 모델은 Rails MVC에서 근본적으로 분리되어 있으므로 컨트롤러는 연결된 모델을 알 수 없습니다.
예를 들어 post라는 모델이있을 수 있습니다. 여기에는 posts_controller 컨트롤러가 있거나 article_controller와 같은 컨트롤러가있을 수 있습니다. Rails는 컨트롤러에서 다음과 같은 실제 코드를 정의 할 때만 모델에 대해 알고 있습니다.
def index
@posts = Post.all
@posts = Article.all
end
Rails 표준 컨트롤러에서는 모델이 무엇인지 알 수있는 방법이 없습니다.
내 컨트롤러와 모델의 네임 스페이스가 지정 되었기 때문에 허용 된 솔루션이 작동하지 않았습니다. 대신 다음과 같은 방법을 생각해 냈습니다.
def controllers_model
(self.class.name.split('::')[0..-2] << controller_name.classify).join('::')
end
반응형
'IT story' 카테고리의 다른 글
AngularJS : ngInclude 대 지시문 (0) | 2020.08.30 |
---|---|
numpy dot ()과 Python 3.5+ 행렬 곱셈의 차이점 @ (0) | 2020.08.30 |
C ++에서 비공개 정적 const 맵을 초기화하는 방법은 무엇입니까? (0) | 2020.08.29 |
초점을 잃어버린 DOM에서 사라지는 html 요소를 어떻게 검사 할 수 있습니까? (0) | 2020.08.29 |
지킬 게시물이 생성되지 않았습니다. (0) | 2020.08.29 |