Ruby on rails Rails链接\u以创建无效链接
我使用的是RubyonRailsV4,我遇到了一个奇怪的问题,我无法找到原因。我有一个rails视图,在其中我试图创建一个到记录的简单链接。在我看来,我正在使用Ruby on rails Rails链接\u以创建无效链接,ruby-on-rails,routing,Ruby On Rails,Routing,我使用的是RubyonRailsV4,我遇到了一个奇怪的问题,我无法找到原因。我有一个rails视图,在其中我试图创建一个到记录的简单链接。在我看来,我正在使用 <%= link_to contact.first_name + " " + contact.last_name, contact %> 这会将我带到应用程序的联系人页面,而不是显示ID为5的联系人 这就是我的simplified routes.rb的样子 Rails.application.routes.draw do
<%= link_to contact.first_name + " " + contact.last_name, contact %>
这会将我带到应用程序的联系人页面,而不是显示ID为5的联系人
这就是我的simplified routes.rb的样子
Rails.application.routes.draw do
root 'dashboard#index'
get 'help' => 'static_pages#help'
get 'about' => 'static_pages#about'
get 'contact' => 'static_pages#contact'
resources :customers
resources :contacts
end
以下是我的路线:
root GET / dashboard#index
help GET /help(.:format) static_pages#help
about GET /about(.:format) static_pages#about
contact GET /contact(.:format) static_pages#contact
customers GET /customers(.:format) customers#index
POST /customers(.:format) customers#create
new_customer GET /customers/new(.:format) customers#new
edit_customer GET /customers/:id/edit(.:format) customers#edit
customer GET /customers/:id(.:format) customers#show
PATCH /customers/:id(.:format) customers#update
PUT /customers/:id(.:format) customers#update
DELETE /customers/:id(.:format) customers#destroy
contacts GET /contacts(.:format) contacts#index
POST /contacts(.:format) contacts#create
new_contact GET /contacts/new(.:format) contacts#new
edit_contact GET /contacts/:id/edit(.:format) contacts#edit
GET /contacts/:id(.:format) contacts#show
PATCH /contacts/:id(.:format) contacts#update
PUT /contacts/:id(.:format) contacts#update
DELETE /contacts/:id(.:format) contacts#destroy
当我使用与上面相同的语法链接到客户时,链接工作正常。我搞砸了什么?为什么当链接上写着contact时,它会向我发送联系人页面
谢谢。路线中的线路。rb给出了以下冲突:
get 'contact' => 'static_pages#contact'
这是因为您已经定义了一个提供联系人url帮助程序的路由: 这意味着您可以使用contact_url或contact_path获取到静态联系人页面的路由 当rails尝试链接到一个对象时,它会对该对象类型使用url帮助器方法。因此,当您链接到…,contact时,它使用现有的contact\u url方法生成路由 您也可以看到客户和联系人之间rake路由输出的差异。对于客户,您可以从show action行获得不同的输出:
customer GET /customers/:id(.:format) customers#show
对于联系人,请选择缺少的联系人:
GET /contacts/:id(.:format) contacts#show
因为已经定义了联系人路由
您可以通过为静态联系人路由定义不同的名称来解决此问题:
get 'contact', to: 'static_pages#contact', as: :static_contact
谢谢@Shadwell。当我运行rake routes时,我注意到客户和联系人是不同的,但我不知道为什么。也谢谢你告诉我如何改变它。我是rails新手,这对我很有帮助。
GET /contacts/:id(.:format) contacts#show
get 'contact', to: 'static_pages#contact', as: :static_contact