带有“_path"的未定义方法使用 rails form_for 时 [英] Undefined method with "_path" while using rails form_for

查看:38
本文介绍了带有“_path"的未定义方法使用 rails form_for 时的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

我在使用 Rails form_for 帮助程序时遇到了(我认为)路由错误.我一直在四处寻找并查看这个问题,但复数对于带有复数的static_event"是static_events",所以我不知所措.任何帮助将不胜感激.详情如下....

I'm running into a (I think) routing error while using the Rails form_for helper. I have been searching around and looked at this question, but the plural for "static_event" with pluralize is "static_events" so I am at a loss. Any help would be apprecited. Here are the details....

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 %>

推荐答案

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

Only routes created using the resources method are automatically named.

如果你想命名你的路线,使用 :as 选项:

If you want to name your routes, use the :as option:

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 方法.您必须将模型的真实"名称作为第一个参数传递,然后根据需要覆盖路径:

However, it's better to use the resources method. You must pass the "true" name of your model as the first parameter, then override the path if you want:

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

这篇关于带有“_path"的未定义方法使用 rails form_for 时的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆