Search code examples
activerecordruby-on-rails-5actionpack

Get data for belongs_to Two Parents rails 5


I have a class like the following:

class Child < ApplicationRecord
  belongs_to :father
  belongs_to :mother
end 

My goal is to create endpoints

  • base-url/father/children #get all children for father
  • base-url/mother/children #get all children for mother

I'm wondering what the correct way of nesting these resources would be I know I can do it one way like:

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

But how can I get the same for base-url/mother/children, is this possible through nested resources? I know I can code the routes.rb to point at a specific controller function if I need to but I would like to understand if I'm missing something, i'm unsure from reading the active record and action pack docs if I am.


Solution

  • The Implementation I went with is as follows: My child controller:

      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 file:

    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 #get all children for mother
    • base_url/father/{father_id}/children #get all children for father