我有一个像下面这样的课程:
class Child < ApplicationRecord
belongs_to :father
belongs_to :mother
end
我的目标是创建端点
我想知道嵌套这些资源的正确方法是什么,我知道我可以采用以下一种方法:
class ChildrenController < ApplicationController
before action :set_father, only: %i[show]
def show
@children = @father.children.all
render json: @children
end
...
但是如何通过base-url / mother / children获得相同的信息,这是否可以通过嵌套资源实现?我知道我可以根据需要编写代码以指向特定的控制器功能,但是我想了解是否遗漏了一些东西,我不确定是否要阅读活动记录和操作包文档。
我使用的实现如下:我的子控制器:
def index
if params[:mother_id]
@child = Mother.find_by(id: params[:mother_id]).blocks
render json: @child
elsif params[:father_id]
@child = Father.find_by(id: params[:father_id]).blocks
render json: @child
else
redirect_to 'home#index'
end
end
...
我的routes.rb文件:
Rails.application.routes.draw do
resources :mother, only: [:index] do
resources :child, only: [:index]
end
resources :father, only: [:index] do
resources :child, only: [:index]
end
...
本文收集自互联网,转载请注明来源。
如有侵权,请联系[email protected] 删除。
我来说两句