ruby on rails - Couldn't find [model] without an ID with has_many through association -


i have 3 models - mom, dad , kid. mom , dad belong each other through kid, associations this:

class kid < activerecord::base   belongs_to :mom   belongs_to :dad end  class mom < activerecord::base   has_many :kids   has_many :dads, through: :kids end  class dad < activerecord::base   has_many :kids   has_many :moms, through: :kids end 

i'm trying route dads' moms searching mom , not one's through kids of dad:

http://localhost:3000/dads/superdad/moms  resources :dads   resources :kids   resources :moms end 

in moms controller tried find id of "superdad":

def index    @dad = dad.find(params[:id])    if params[:q].present?      @moms = mom.search(params[:q], page: params[:page], per_page: 25)    else      @moms = mom.none    end end 

but run error:

couldn't find dad without id   # line 8 @dad = dad.find(params[:id]) 

is possible use @dad in way when mom has no direct id towards it? suggest do? need @dad.name (and more) on mom's index page.

use this:

def index    @dad = dad.find(params[:dad_id])    if params[:q].present?      @moms = mom.search(params[:q], page: params[:page], per_page: 25)    else      @moms = mom.none    end end 

use params[:dad_id] instead of params[:id]. reason route generated index action of momscontroller be:

dad_moms    /dads/:dad_id/moms(.:format)          moms#index 

params[:dad_id] give dad_id superdad http://localhost:3000/dads/superdad/moms. in case, looking params[:id] not exist. hence, error.


Comments

Popular posts from this blog

PHPMotion implementation - URL based videos (Hosted on separate location) -

c# - Unity IoC Lifetime per HttpRequest for UserStore -

I am trying to solve the error message 'incompatible ranks 0 and 1 in assignment' in a fortran 95 program. -