form_for with :slug instead of :id

352 Views Asked by At
<%= form_for [current_user, @task] do |f| %>

gives users/:id/tasks but I would need users/:slug/tasks as I am using:

resources :users, param: :slug do
  resources :tasks, only: [:index, :new, :create]
end

but if I use:

<%= form_for [current_user.slug, @task] do |f| %>

I get: NoMethodError: undefined method 'jemelle_visits_path' for

how to get users/jemelle/tasks instead?

1

There are 1 best solutions below

3
On BEST ANSWER

I think you need to override the to_param method of your model:

https://apidock.com/rails/ActiveRecord/Base/to_param

user = User.find_by_name('Phusion')
user_path(user)  # => "/users/1"

You can override to_param in your model to make user_path construct a path using the user’s name instead of the user’s id:

class User < ActiveRecord::Base
  def to_param  # overridden
    name
  end
end

user = User.find_by_name('Phusion')
user_path(user)  # => "/users/Phusion"