使用rails form_for时使用“_path”的未定义方法

时间:2012-01-03 00:36:51

标签: ruby-on-rails ruby

在使用Rails form_for帮助程序时,我遇到了(我认为)路由错误。我一直在寻找this question,但复数形式的“static_event”的复数是“static_events”,所以我很茫然。任何帮助都会得到赞赏。这是详细信息....

ActionView::Template::Error (undefined method `static_events_path' for #<#<Class:0x007f9fcc48a918>:0x007f9fcc46fa78>):

我的模特:

class StaticEvent < ActiveRecord::Base
attr_accessible :content, :title, :discount, :location, :day_of_week, :start_time

我的控制器:

    class StaticEventsController < ApplicationController

  before_filter :authenticate, :only => [:create, :destroy]
  before_filter :authorized_user, :only => [:destroy] 


  def new
    @title = "Share An Event"
    @static_event = StaticEvent.new 
  end

  def create
    @static_event = current_user.static_events.build(params[:event])
    if @static_event.save
      flash[:success] = "Event Shared"
      redirect_to @static_event #this was the old version
    else
      render :new
    end
  end

路线:

match '/static-events/new', :to => 'static_events#new'
match '/static-events/',     :to => 'static_events#index'
match '/static-events/:id', :to => 'static_events#show'

视图

<%= form_for (@static_event) do |f| %>
<%= render 'shared/error_messages', :object => f.object %>
<%= text_field "static_event", "title", "size" => 48 %>
<%= time_select "static_event", "start_time", {:ampm => true, :minute_step => 15} %>
<%= text_area "static_event", "content", "cols" => 42, "rows" => 5 %>
<%= text_field "static_event", "discount", "size" => 48 %>
<%= text_field "static_event", "location", "size" => 48 %>
<%= text_field "static_event", "day_of_week", "size" => 48 %>
<input name="" type="submit" class="button" value="share on chalkboard" />
<% end %>

4 个答案:

答案 0 :(得分:28)

只有使用resources方法创建的路径才会自动命名。

如果您想为路线命名,请使用:as选项:

match '/static-events/new', :to => 'static_events#new', :as => :new_static_event
match '/static-events/',     :to => 'static_events#index', :as => :static_events
match '/static-events/:id', :to => 'static_events#show', :as => :static_event

但是,最好使用resources方法。您必须将模型的“true”名称作为第一个参数传递,然后根据需要覆盖路径:

resources :static_events, :path => 'static-events'

答案 1 :(得分:9)

首先,您应该以这种方式定义路线:

resources 'static-events', :only => [:new, :create]

这将为new和create方法创建一个路径。

因为当您使用新的ActiveRecord对象作为for的参数时,它将使用POST谓词在路由文件中查找类似static_events_path的* s_path。

我认为你定义你的路由的方式不会创建带有POST动词的static_events_path(你可以通过使用rake路由来检查那个megas说的)。所以不要再使用匹配,使用资源或获取/发布/ ...而不是在Rails 3项目中匹配。

修改

我昨天没有注意到,但是没有创建方法的路线。在 static_events #index 之前添加以下路线,或者删除所有路线,并按照我上面的说法进行操作。

post '/static-events/', :to => 'static_events#create'

答案 2 :(得分:5)

运行rake routes,您将看到路线列表。然后,您可以修复路径文件以获得适当的路径路径。

答案 3 :(得分:2)

当我使用嵌套资源时发生这种情况,但忘记在cancan中使用load_and_authorize_resource实际初始化父资源。因此,父资源为null并且它抛出了此错误。

我通过在控制器中的父级声明load_and_authorize_resource来修复它。