gpt4 book ai didi

ruby-on-rails - form_for 与 :slug instead of :id

转载 作者:行者123 更新时间:2023-12-04 08:46:31 25 4
gpt4 key购买 nike

<%= 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"

关于ruby-on-rails - form_for 与 :slug instead of :id,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/64288293/

25 4 0
Copyright 2021 - 2024 cfsdn All Rights Reserved 蜀ICP备2022000587号
广告合作:1813099741@qq.com 6ren.com