hashrocket / decent_exposure

A helper for creating declarative interfaces in controllers
MIT License
1.81k stars 107 forks source link

Pass param to new action for nested resource #170

Closed lunij closed 7 years ago

lunij commented 7 years ago

With version 3 of decent_exposure it is not possible to provide a non-empty param to build a new record using the new method. That seem to be a problem with required nested resources.

class ThingsController < ApplicationController
  expose :thing_group
  expose :thing

  # GET -> https://example.com/thing_groups/7/things/new
  # expected: Thing.new(thing_group: 7)
  # actual: Thing.new
  def new
  end

  # POST/PUT/PATCH -> https://example.com/thing_groups/7/things
  # expected: Thing.new(thing_group: 7, thing_params)
  # actual: Thing.new(thing_params)
  def create
  end

  private

  def thing_params
    params.require(:thing).permit(:something)
  end
end

A partial solution to fix the new action could be:

expose :thing, build_params: ->{ { thing_group_id: thing_group.id } }

Problem: It does not work with the create action because of the not included strong parameters method thing_params.

A partial solution to fix the create action could be:

expose :thing, build_params: ->{ { thing_group_id: thing_group.id }.merge(thing_params) }

Problem: It crashes with the new action because of the thing_params method that requires a thing key in the params hash.

So how is this intended to work?

14tinchov commented 7 years ago

You could merge the thing_group in the parameters, although I think it isn't the right way

def thing_params
    params.require(:thing).permit(:something).merge(thing_group: thing_group)
end

Edit: Use expose :thing, parent: thing_group