Home > database >  How to add param to single action route in Rails?
How to add param to single action route in Rails?

Time:07-25

I have a nested route denoting a single action, which works as expected in the following way:

resources :abilities, param: :slug do
  delete '/company/:slug', controller: :ability_companies, action: :destroy
end

However, all my routes are defined as symbols, with the param name defined as an attribute, and I'd like to keep my route definitions coherent.

The following syntax seems to follow the logic I use elsewhere, but it doesn't work and I cannot figure out why.

delete :company, controller: :ability_companies, action: :destroy, param: :slug

With the above line, I get a 404 error. What am I overlooking here?

CodePudding user response:

on config/routes.rb

resources :abilities, only: [ :destroy ], as: :destroy

on app/controllers/ability_contoller.rb

  def destroy
    @ability = Ability.find(params[:my_params])
    @ability.destroy
    redirect_to any_path
  end

  private
  def my_params
    params.require(:abilities).permit(:slug )
  end

CodePudding user response:

I ended up treating the nested route as a nested resource. The result is more semantic (plural "companies") and cleaner as well, given how 90% of my routes are handled on a resource-level.

The resulting lines of code:

resources :abilities, param: :slug do
  resources :companies, controller: :ability_companies, param: :company_slug, only: [:destroy, :create]
end
  • Related