我有一个类似以下的课程:
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
...
但是我如何通过基本资源/母亲/孩子获得相同的资源,这是否可以通过嵌套资源实现?我知道我可以编写代码,如果需要的话可以指向特定的控制器功能,但是我想了解我是否缺少什么,我不确定是否要阅读活动记录和操作包文档。
我使用的实现如下:我的孩子控制器:
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
...