【问题标题】:Get data for belongs_to Two Parents rails 5获取belongs_to 两个父母的数据 rails 5
【发布时间】:2019-12-12 17:15:25
【问题描述】:

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

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
... 

但是我怎样才能得到相同的 base-url/mother/children,这可以通过嵌套资源实现吗? 我知道如果需要,我可以对 routes.rb 进行编码以指向特定的控制器功能,但我想了解我是否遗漏了某些内容,如果我是,我不确定是否阅读活动记录和操作包文档。

【问题讨论】:

  • 在这种情况下,您应该有一个用于父亲/孩子的端点和其他用于母亲/孩子的端点,这意味着控制器中有两条路线和两个动作。

标签: activerecord ruby-on-rails-5 actionpack


【解决方案1】:

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

  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/{father_id}/children #获取父亲的所有孩子

【讨论】:

    猜你喜欢
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 2022-11-20
    • 2017-05-16
    • 1970-01-01
    相关资源
    最近更新 更多