jeudi 3 mars 2016

show method for controller on a has_one association

I have two models

thing.rb
has_one :subthing

subthing.rb
belongs_to :thing

And am routing with

resources :thing do
  resource :subthing
end

resources :subthing

However, my show method on my controller

def show
  @subthing = Subthing.find(params[:id])
end

when I visit

http://ift.tt/1OUjVGh

is giving me an error

Couldn't find Subthing without an ID

I sort of feel like this should be being taken care of by the framework... i.e it should work out that the relevant Subthing is the one that belongs to Thing.

Am I missing something or can I not use the same controller method here for Subthings on their own and Subthings when they're part of a thing.

Or do I need to explicitly tell the controller for each potential association. i.e.

def show
  if params[:thing_id].present?
    @subthing = @thing.find(params[:thing_id]).subthing
  else
    @subthing = Subthing.find(params[:id])
  end
end

Aucun commentaire:

Enregistrer un commentaire