Activerecord 获取属于两个父rails 5的数据
我的课程如下:Activerecord 获取属于两个父rails 5的数据,activerecord,ruby-on-rails-5,actionpack,Activerecord,Ruby On Rails 5,Actionpack,我的课程如下: class Child < ApplicationRecord belongs_to :father belongs_to :mother end class-Child
class Child < ApplicationRecord
belongs_to :father
belongs_to :mother
end
class-Child
我的目标是创建端点
- 基本url/父亲/子女#为父亲获取所有子女
- 基本url/母亲/子女#为母亲获取所有子女
class ChildrenController < ApplicationController
before action :set_father, only: %i[show]
def show
@children = @father.children.all
render json: @children
end
...
class-ChildrenController
但是我如何才能获得相同的基本url/母亲/子女,这是通过嵌套资源实现的吗?
我知道,如果需要,我可以将routes.rb编码为指向特定控制器功能,但我想了解,如果我遗漏了什么,我不确定是否阅读了活动记录和操作包文档。我使用的实现如下: 我的孩子控制器:
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
...
My 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#为母亲获取所有孩子
- base_url/father/{father_id}/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
...
My 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#为母亲获取所有孩子
- base_url/father/{father_id}/children#为父亲获取所有孩子