Rails 4编辑表单无法找到路径

时间:2015-05-28 01:52:33

标签: ruby-on-rails ruby ruby-on-rails-4

我正在做一个简单的CRUD,我遇到edit/update的问题。这就是我的表单的样子:

= simple_form_for @receipt do |f|
  = render 'shared/error_messages', object: @receipt
  = f.input :purchase_date, as: :string, input_html: {'data-provide' => 'datepicker'}
  = f.input :amount, as: :string, input_html: {'data-provide' => 'datepicker'}
  = f.association :store

因此,对于新动作,我在视图中有这个:

h2 Create new receipt
  = render 'form'

我在新控制器操作中初始化我的@receipt实例变量。但是,当我尝试编辑时,这是编辑视图的内容:

h2 Edit receipt
  = render 'form'

我收到此错误:

undefined method `receipt_path' for #<#<Class:0x007f943b6f3750>:0x007f943d5ce5d0>

form部分的第一行。这就是我的路线的样子:

resource :receipts do
    collection do
      get :index
    end
end

关于路线的奇怪之处在于,在我没有添加get :index的情况下,索引的路由不会生成,这是我的rake routes的索引输出出现在资源集合中:

receipts GET    /receipts(.:format)      receipts#index
              POST   /receipts(.:format)      receipts#create
 new_receipts GET    /receipts/new(.:format)  receipts#new
edit_receipts GET    /receipts/edit(.:format) receipts#edit
              GET    /receipts(.:format)      receipts#show
              PATCH  /receipts(.:format)      receipts#update
              PUT    /receipts(.:format)      receipts#update
              DELETE /receipts(.:format)      receipts#destroy

我的意思是我可以将网址传递给编辑和新形式,这将使其工作我猜。它过去是多余的。

我的问题是我在这里做错了什么,这是我第一个使用rails 4的项目,这是一个rails 4的东西吗?

更新 根据注释,我没有使用控制器中的实例变量,而是将新的局部变量传递给部分,如下所示:

= render 'form', object: @receipt

并将形式改为:

= simple_form_for object do |f|

仍然得到与实例变量相同的结果。

2 个答案:

答案 0 :(得分:1)

resource替换为resources,然后移除get :index。它可以解决您的问题

答案 1 :(得分:-1)

请将resource :receipts替换为resources :receipts 我希望这能解决你的问题。

您也不需要添加get "index"操作,因为resources关键字会自行提供CRUD操作,例如(索引,新建,编辑等)