【发布时间】:2014-09-10 16:38:08
【问题描述】:
我不明白为什么 ActiveRecord 在我的 ContactsController 中寻找 id='new'!请帮助这是我第一次使用 Ruby on Rails 练习。我所有的其他路线都有效,但我的get "contacts/new" 路线。我不确定这是怎么回事,但是,当我单击索引页面中的链接时,显示路线/页面可以正常工作,但是当我尝试创建新联系人时,我的新路线不起作用,并且它说错误出现在我的显示方法中在控制器的最底部。请帮助,我是使用 Rails 框架的新手。
Routes.rb
RailsPortfolio::Application.routes.draw do
get "contacts" => 'contacts#index', :as => "contact_list"
get "contacts/:id" => 'contacts#show', :as => "contact"
get "contacts/new" => 'contacts#new', :as => "contact_new"
get "contacts/:id/edit" => 'contact#edit', :as => "contact_edit"
post "contacts" => 'contacts#create'
put "contacts/:id" => 'contacts#update'
end
contacts_controller.rb
class ContactsController < ApplicationController
def index
@contacts = Contact.all
end
def new
@contact = Contact.new
end
binding.pry
def create
@contact = Contact.new(params[:contact])
if @contact.save
redirect_to contact_list_path
else
render "new"
end
end
def edit
@existing_contact = Contact.find(params[:id])
end
def update
@existing_contact = Contact.find(params[:id])
if @existing_contact.update_attributes(params[:contact])
redirect_to contact_list_path(@existing_contact.id)
else
render "edit"
end
end
def show
@contact = Contact.find(params[:id])
end
end
【问题讨论】:
-
resources :contacts在您的路线中就足够了 -
在路由文件中,您可以对所有路由使用较短的版本,例如资源:联系人
-
感谢@nithin,我的导师还没有教我们用于 CRUD 操作的资源指令。不知道为什么,但我以后会记得的。下面的人暂时解决了我的问题。只需要将我的表演路线移到底部即可。
-
@bigREDcode okies,您可以接受解决问题的答案。
标签: ruby-on-rails ruby activerecord routing