我有一个User
模型和一个Storefront
模型。
由于某种原因,当我尝试去/storefronts/new时,我得到这个错误:
路由错误没有匹配{:action=>"edit",:controller=>"storefronts"的路由,:id=># Storefront id: nil, name: nil, user_id: 4, created_at: nil,Updated_at: nil, description: nil, location: nil>}
我花了3个小时想弄明白。它昨天还在工作……为什么它说:action=>"edit"当它是'new' action?
下面是我的代码:
class Storefront < ActiveRecord::Base
attr_accessible :name, :location, :description
belongs_to :user
end
class User < ActiveRecord::Base
attr_accessible :name, :email, :password, :password_confirmation
has_secure_password
has_one :storefront
end
class StorefrontsController < ApplicationController
before_filter :check_auth, only: [:new, :edit, :update]
def index
@storefronts = Storefront.all
end
def new
@storefront = current_user.build_storefront
end
def create
@storefront = current_user.build_storefront(params[:storefront])
if @storefront.save
redirect_to edit_storefront_path(@storefront)
else
render 'new'
end
end
def show
@storefront = Storefront.find(params[:id])
end
def edit
@storefront = Storefront.find(params[:id])
end
def update
@storefront = Storefront.find(params[:id])
if @storefront.update_attributes(params[:storefront])
redirect_to @storefront
else
render 'edit'
end
end
end
Pbf::Application.routes.draw do
resources :sessions, :only => [:new, :create, :destroy]
resources :users
resources :storefronts
root :to => 'storefronts#index'
match '/signup', to: 'users#new'
match '/login', to: 'sessions#new'
match '/logout', to: 'sessions#destroy'
end
使用<<p>链接我strong>(的问题): <% if current_user.storefront %>
<%= link_to "Manage Storefront", edit_storefront_path(current_user.storefront) %>
<% else %>
<%= link_to "Open Storefront!", openstore_path %>
<% end %>
提前感谢!
编辑:我的rake routes
sessions POST /sessions(.:format) sessions#create new_session GET /sessions/new(.:format) sessions#new session DELETE /sessions/:id(.:format) sessions#destroy users GET /users(.:format) users#index POST /users(.:format) users#create new_user GET /users/new(.:format) users#new edit_user GET /users/:id/edit(.:format) users#edit user GET /users/:id(.:format) users#show PUT /users/:id(.:format) users#update DELETE /users/:id(.:format) users#destroy storefronts GET /storefronts(.:format) storefronts#index POST /storefronts(.:format) storefronts#create new_storefront GET /storefronts/new(.:format) storefronts#new edit_storefront GET /storefronts/:id/edit(.:format) storefronts#edit storefront GET /storefronts/:id(.:format) storefronts#show PUT /storefronts/:id(.:format) storefronts#update DELETE /storefronts/:id(.:format) storefronts#destroy
在我看来你的视图中有一个错误。app/views/storefronts/new.html.erb
错误地引用edit_storefront_path
而没有传递storefront_id
作为参数。你可能需要storefronts_path
问题可能是路由器无法从某种':id'中找出'new'。尝试在编辑路由声明中添加约束
get 'storefronts/:id/edit' => 'storefronts#edit', :id => /[d]*/
那么只有数字id将被解释为编辑操作的调用。
这是new_storefronts_path
,它是集合路由,如果你传递的是单数形式,那么如果你没有声明任何命名路由,它就被认为是成员路由。这就是为什么路由选择编辑动作,关于id 4,你没有按照约定传递id,所以nil.object_id
是4。