获取 belongs_to 两个 Parents rails 5 的数据
Get data for belongs_to Two Parents rails 5
我有一个 class 如下所示:
class Child < ApplicationRecord
belongs_to :father
belongs_to :mother
end
我的目标是创建端点
- base-url/father/children #get all children for father
- base-url/mother/children #get all children for mother
我想知道嵌套这些资源的正确方法是什么我知道我可以用一种方法来做到这一点:
class ChildrenController < ApplicationController
before action :set_father, only: %i[show]
def show
@children = @father.children.all
render json: @children
end
...
但是我怎样才能得到相同的 base-url/mother/children,这可以通过嵌套资源实现吗?
我知道如果需要,我可以对 routes.rb 进行编码以指向特定的控制器功能,但我想了解我是否遗漏了什么,我不确定如果我阅读活动记录和操作包文档上午
我的实现如下:
我的 child 控制器:
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
...
- base_url/mother/{mother_id}/children #得到所有children给妈妈
- base_url/father/{father_id}/children #获取所有children for father
我有一个 class 如下所示:
class Child < ApplicationRecord
belongs_to :father
belongs_to :mother
end
我的目标是创建端点
- base-url/father/children #get all children for father
- base-url/mother/children #get all children for mother
我想知道嵌套这些资源的正确方法是什么我知道我可以用一种方法来做到这一点:
class ChildrenController < ApplicationController
before action :set_father, only: %i[show]
def show
@children = @father.children.all
render json: @children
end
...
但是我怎样才能得到相同的 base-url/mother/children,这可以通过嵌套资源实现吗? 我知道如果需要,我可以对 routes.rb 进行编码以指向特定的控制器功能,但我想了解我是否遗漏了什么,我不确定如果我阅读活动记录和操作包文档上午
我的实现如下: 我的 child 控制器:
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
...
- base_url/mother/{mother_id}/children #得到所有children给妈妈
- base_url/father/{father_id}/children #获取所有children for father