2
<%= 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 Answer 1

2

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"
Sign up to request clarification or add additional context in comments.

3 Comments

this surprisingly work.. I told you didn't understand the question at first. Is that #to_param overwriting the method that form_for uses to translate the argument into a path?
yes it does just that, and I could change User#name to my User#slug
form_for uses the type of the object to infer it has to call user_path, and then user_path calls .to_param on that object (to_param defaults to the id)

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.