1
votes

I have a nested resource (child) that is only viewed and edited on its parent's resource views. How to make error messages of the child display on its parent's views when an action of the child is called and the child is invalid?

In order to do this I have the child's action in the parent's controller now. But I'd like to have it in the child's controller where it belongs, i.e. I'd like the activate action in the placements_controller rather than activate_placement action in the recipients_controller.

routes.rb:

# Present setup:
patch '/recipients/:recipient_id/placements/:id/activate' =>
  'recipients#activate_placement', :as => :activate_recipient_placement
# Placement is activated (and validated) by recipients_controller.
# If errors exist, recipient's show view with that placement is rendered 
# displaying the placement's error messages. I want that. 
# But I'd like the activate action to be in the placements_controller.

# Preferred setup:
resources :recipients do
  ...
  resources :placements do
    patch 'activate' on: :member
  end
end
# Now, placement is activated (and validated) by placements_controller.
# But if errors exist on the placement, the placement's own show view,
# rather than the parent's show view, is rendered with the error messages.
1

1 Answers

0
votes

The setup should be in their own controllers

Nested resources are mainly for routing structures, but also ensure you're able to accommodate the right data in the right places of the app


Code

#config/routes.rb
resources :recipients do 
    resources :placements #-> /recipients/5/placements/new
end

#app/controllers/placements_controller.rb
def new
   @placement = Placement.new
end

def create
   @placement = Placement.new(placement_params)
   @placement.save
end 

private

def placement_params
    params.require(:placement).permit(:info, :about, :placement).merge(recipient_id: params[:recipient_id])
end

If you'd like us to be more specific, you'll have to provide some more code :)