获取归属数据到两个Parent rails 5

问题描述 投票:1回答:1

我有一个类似以下的课程:

class Child < ApplicationRecord
  belongs_to :father
  belongs_to :mother
end 

我的目标是创建端点

  • base-url / father / children#把所有孩子都给父亲
  • base-url / mother / children#把所有孩子都给妈妈

我想知道嵌套这些资源的正确方法是什么,我知道我可以采用以下一种方法:

class ChildrenController < ApplicationController
  before action :set_father, only: %i[show] 
  def show
     @children = @father.children.all
    render json: @children
  end
... 

但是我如何通过基本资源/母亲/孩子获得相同的资源,这是否可以通过嵌套资源实现?我知道我可以编写代码,如果需要的话可以指向特定的控制器功能,但是我想了解我是否缺少什么,我不确定是否要阅读活动记录和操作包文档。

activerecord ruby-on-rails-5 actionpack
1个回答
0
投票

我使用的实现如下:我的孩子控制器:

  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#让所有孩子都当妈妈
  • base_url /父亲/ {father_id} / children#为父亲生下所有孩子
© www.soinside.com 2019 - 2024. All rights reserved.