(Ruby 在 Rails 上)在 routes.rb 中构建 URL
(Ruby on Rails) Building a URL in routes.rb
我是 Rails 的新手,请耐心等待。
我正在尝试构建以下 URL:
localhost:3000/products/toyota
因此,主页(localhost:3000 当我在本地 运行 项目时)和产品页面 (localhost:3000/products) 已经存在,但我正在尝试创建一个丰田页面 (localhost:3000/products/toyota)。丰田页面有自己的视图 (haml page/javascript),独立于产品页面。
所以,我在 config/routes.rb
中尝试了这个
get 'toyota', to: 'static#products#toyota'
但是 toyota_url 将我带到 localhost:3000/toyota 而不是 localhost:3000/products/toyota。
关于如何解决这个问题有什么想法吗?
你需要这个
get '/products/toyota', to: 'static#products#toyota', as: 'toyota'
希望对您有所帮助!
正如评论中所述:它是 get 'my/full/path', to: ....
所以尝试 get 'products/toyota', to: 'static#products#toyota', :as => 'toyota'
但我会推荐以下内容。为了让它更灵活一点——我假设你还有其他 vendors/products,创建一个动作:
路线:
get 'products/:vendor', to: 'products#vendor'
控制器:
def vendor(id)
@car_or_whatever = Product.find_by(....)
end
查看:
# file views/products/vendor.html.erb
<some fancy html>
@car_or_whatever.name
... etc
来自文档:http://guides.rubyonrails.org/routing.html#generating-paths-and-urls-from-code
我是 Rails 的新手,请耐心等待。 我正在尝试构建以下 URL:
localhost:3000/products/toyota
因此,主页(localhost:3000 当我在本地 运行 项目时)和产品页面 (localhost:3000/products) 已经存在,但我正在尝试创建一个丰田页面 (localhost:3000/products/toyota)。丰田页面有自己的视图 (haml page/javascript),独立于产品页面。
所以,我在 config/routes.rb
中尝试了这个get 'toyota', to: 'static#products#toyota'
但是 toyota_url 将我带到 localhost:3000/toyota 而不是 localhost:3000/products/toyota。
关于如何解决这个问题有什么想法吗?
你需要这个
get '/products/toyota', to: 'static#products#toyota', as: 'toyota'
希望对您有所帮助!
正如评论中所述:它是 get 'my/full/path', to: ....
所以尝试 get 'products/toyota', to: 'static#products#toyota', :as => 'toyota'
但我会推荐以下内容。为了让它更灵活一点——我假设你还有其他 vendors/products,创建一个动作:
路线:
get 'products/:vendor', to: 'products#vendor'
控制器:
def vendor(id)
@car_or_whatever = Product.find_by(....)
end
查看:
# file views/products/vendor.html.erb
<some fancy html>
@car_or_whatever.name
... etc
来自文档:http://guides.rubyonrails.org/routing.html#generating-paths-and-urls-from-code