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

Ale*_*ekx 34 ruby ruby-on-rails

我在使用Rails form_for帮助程序时遇到(我认为)路由错误.我一直在寻找这个问题,但复数形式的"static_event"是"static_events",所以我很茫然.任何帮助都会得到赞赏.这是细节....

ActionView::Template::Error (undefined method `static_events_path' for #<#<Class:0x007f9fcc48a918>:0x007f9fcc46fa78>):
Run Code Online (Sandbox Code Playgroud)

我的型号:

class StaticEvent < ActiveRecord::Base
attr_accessible :content, :title, :discount, :location, :day_of_week, :start_time
Run Code Online (Sandbox Code Playgroud)

我的控制器:

    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
Run Code Online (Sandbox Code Playgroud)

路线:

match '/static-events/new', :to => 'static_events#new'
match '/static-events/',     :to => 'static_events#index'
match '/static-events/:id', :to => 'static_events#show'
Run Code Online (Sandbox Code Playgroud)

风景

<%= 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 %>
Run Code Online (Sandbox Code Playgroud)

Fáb*_*sta 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
Run Code Online (Sandbox Code Playgroud)

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

resources :static_events, :path => 'static-events'
Run Code Online (Sandbox Code Playgroud)


bas*_*gys 9

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

resources 'static-events', :only => [:new, :create]
Run Code Online (Sandbox Code Playgroud)

这将为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'
Run Code Online (Sandbox Code Playgroud)


meg*_*gas 5

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