form_for 用 :slug 代替 :id
form_for with :slug instead of :id
<%= form_for [current_user, @task] do |f| %>
给出 users/:id/tasks
但我需要 users/:slug/tasks
因为我正在使用:
resources :users, param: :slug do
resources :tasks, only: [:index, :new, :create]
end
但如果我使用:
<%= form_for [current_user.slug, @task] do |f| %>
我得到:NoMethodError: undefined method 'jemelle_visits_path' for
如何获取 users/jemelle/tasks
?
我认为您需要覆盖模型的 to_param
方法:
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"
<%= form_for [current_user, @task] do |f| %>
给出 users/:id/tasks
但我需要 users/:slug/tasks
因为我正在使用:
resources :users, param: :slug do
resources :tasks, only: [:index, :new, :create]
end
但如果我使用:
<%= form_for [current_user.slug, @task] do |f| %>
我得到:NoMethodError: undefined method 'jemelle_visits_path' for
如何获取 users/jemelle/tasks
?
我认为您需要覆盖模型的 to_param
方法:
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"