gpt4 book ai didi

ruby-on-rails - 使用引擎时如何在模型中找到资源路径?

转载 作者:数据小太阳 更新时间:2023-10-29 09:02:25 24 4
gpt4 key购买 nike

在使用 Rails 电子商务引擎 Spree 时,我试图将 products_path 保存在我的 Spree::Product 模型中以进行跟踪。

Looking on SO I found this solution, which looked like the perfect answer.

Rails.application.routes.url_helpers.products_path
Rails.application.routes.url_helpers.products_url(:host => "example.com")

但使用该解决方案只会给我以下错误。

NoMethodError: undefined method `products_path' for #<Module:0x007fe9e208e908>

非常沮丧....

最佳答案

使用 Rails 引擎时,您需要使用引擎的路由助手,而不是主要的 Rails 应用程序路由助手。

Spree::Core::Engine.routes.url_helpers.products_path
Spree::Core::Engine.routes.url_helpers.products_url(:host => "example.com")

额外提示:

如果你想摆脱 :host => "example.com" 参数,你可以在你的环境配置文件中添加一个主机指示符。

就像 url_helpers 一样,对于引擎,您需要在引擎路由下添加默认值。

# in config -> environments -> development.rb

Spree::Core::Engine.routes.default_url_options[:host] = 'localhost:3000'

注意:不会为 Rails.application.routes.url_helpers 设置默认主机 ;-)

关于ruby-on-rails - 使用引擎时如何在模型中找到资源路径?,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/32127234/

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