【问题标题】:No Method Error – Undefined Method for Class没有方法错误 - 类的未定义方法
【发布时间】:2011-07-05 06:20:30
【问题描述】:

所以这简直让我发疯了!我浏览了大量帖子,但无法让我的应用正常工作。我希望 SO 社区可以。

所以,我有一个 RoR 应用程序,我可以在其中创建一个新事件。

当我转到 localhost:3000/events 和 localhost:3000/events/new 时,它们都正确加载并且看起来很棒。这是问题所在。当我在 localhost:3000/events/new 提交事件时,表单信息已添加到数据库中,但出现以下错误:

#

的未定义方法 `event_path'

这里有一些(希望是)相关代码位:

views/events/create.html.erb

<%= simple_form_for(@event) do |f| %>
<%= f.input :name %>
<%= f.input :date %>
<%= f.input :location %>
<%= f.input :organization %>
<%= f.input :description %>
<%= f.submit "Create Event"%>

controllers/events_controller.rb

class EventsController < ApplicationController
respond_to :html

  def index
    @all_events = Event.all
  end

  def show
      @event = Event.find_by_name(params[:id])
  end

  def new
    respond_with(@event = Event.new)
  end

  def edit
    @event = Event.find_by_name(params[:id])
  end

  def create
    @event = Event.create(params[:event])
    if @event.valid?
        flash[:notice] = "Event successfully created"
    end
   end

  def update
@event = Event.find_by_name(params[:id])
@event.update_attributes(params[:event])
if @event.valid?
    flash[:notice] = "Event successfully updated"
end
respond_with(@event)
  end

  def destroy
    @event = Event.find_by_name(params[:id])
    if @event.destroy
        flash[:notice] = "Event successfully deleted"
    end
    respond_with(@event)
  end
end

models/event.rb

   class Event < ActiveRecord::Base
    validates_presence_of :name
    has_and_belongs_to_many :organizations

    attr_accessible :name, :date, :location, :organization, :description
    attr_accessor :organizations

    end

config/routes.rb(仅相关部分)

resources :events, :only => [:index, :new, :create, :edit]

非常感谢可以提供的任何帮助...我是 Ruby on Rails 的新手,所以我只是想弄清楚这一切。

谢谢!

凯文

【问题讨论】:

    标签: ruby-on-rails ruby-on-rails-3 methods controllers


    【解决方案1】:

    创建或更新方法后,您重定向到@event,这将重定向到您的活动的显示页面。您尚未使用:only 子句生成显示、更新、销毁页面的路由。您可以通过在控制台上运行 rake routes 来验证这一点。删除:only clause 即可。

    【讨论】:

    • 感谢您的帮助...我将其更改为仅资源 :events 但现在,当我创建事件时,它仅停留在 /events/new 页面上。如何让它重定向到 /events 页面?谢谢!
    • 在您的 create 方法中,您可以使用 redirect_to @event 根据您的意愿重定向到事件显示页面或任何其他页面(redirect :action => :index),并在 else 中使用 render :new如果表单中有任何错误,则显示新页面。
    猜你喜欢
    • 1970-01-01
    • 1970-01-01
    • 2020-12-24
    • 1970-01-01
    • 2021-02-24
    • 2021-07-26
    • 2021-04-15
    • 2020-05-21
    • 2019-05-10
    相关资源
    最近更新 更多