Rails 在控制器中引用两层深度嵌套
Rails reference two levels deep nest in controller
我有一个两层深度嵌套:
routes.rb
resources :projects do
resources :offers do
resources :reports
end
end
在我使用的控制器中:
before_action :set_project
before_action :set_offer, only: [:show, :edit, :update, :destroy]
.....
def index
@offers = @project.offers
end
.....
def set_project
@project = Project.find(params[:project_id])
end
# Use callbacks to share common setup or constraints between actions.
def set_offer
@offer = @project.offers.find(params[:id])
end
如何在 Reports_controller.rb 中引用报告,就像在报价索引中一样?
同理:
# reports_controller.rb
def index
@reports = Reports.where(project: params[:project_id],
offer: params[:offer_id])
end
def update
@report = Reports.find_by(project: params[:project_id],
offer: params[:offer_id],
id: params[:id])
# rest of update code
end
如果您愿意,可以将此逻辑放入辅助方法中,就像对其他方法所做的那样。
我还要提一下,通常不鼓励像这样嵌套超过一层深度,因为如您所见,它变得有点混乱。我经常使用的一种折衷方案是使用浅资源方法。
一定要查看 this section of the Rails Routing guide 以获取有关此内容以及如何实现浅嵌套的更多信息。它基本上可以让您做到这一点,以便您只需要实际需要该信息的操作的附加参数,但其他操作允许您仅通过其 id
引用资源而无需其他参数。
我有一个两层深度嵌套:
routes.rb
resources :projects do
resources :offers do
resources :reports
end
end
在我使用的控制器中:
before_action :set_project
before_action :set_offer, only: [:show, :edit, :update, :destroy]
.....
def index
@offers = @project.offers
end
.....
def set_project
@project = Project.find(params[:project_id])
end
# Use callbacks to share common setup or constraints between actions.
def set_offer
@offer = @project.offers.find(params[:id])
end
如何在 Reports_controller.rb 中引用报告,就像在报价索引中一样?
同理:
# reports_controller.rb
def index
@reports = Reports.where(project: params[:project_id],
offer: params[:offer_id])
end
def update
@report = Reports.find_by(project: params[:project_id],
offer: params[:offer_id],
id: params[:id])
# rest of update code
end
如果您愿意,可以将此逻辑放入辅助方法中,就像对其他方法所做的那样。
我还要提一下,通常不鼓励像这样嵌套超过一层深度,因为如您所见,它变得有点混乱。我经常使用的一种折衷方案是使用浅资源方法。
一定要查看 this section of the Rails Routing guide 以获取有关此内容以及如何实现浅嵌套的更多信息。它基本上可以让您做到这一点,以便您只需要实际需要该信息的操作的附加参数,但其他操作允许您仅通过其 id
引用资源而无需其他参数。