Rails xxxxx_path 给出 undefined local variable or method 的问题...

blacktulip · 2012年11月28日 · 最后由 blacktulip 回复于 2012年11月28日 · 5061 次阅读

一个简单的事件列表:

route.rb:

...
resources :events

rake route:

      root        /                          menu_pages#home
     about        /about(.:format)           menu_pages#about
  services        /services(.:format)        menu_pages#services
   contact        /contact(.:format)         menu_pages#contact
    events GET    /events(.:format)          events#index
           POST   /events(.:format)          events#create
 new_event GET    /events/new(.:format)      events#new
edit_event GET    /events/:id/edit(.:format) events#edit
     event GET    /events/:id(.:format)      events#show
           PUT    /events/:id(.:format)      events#update
           DELETE /events/:id(.:format)      events#destroy

app/model/event.rb:

# == Schema Information
#
# Table name: events
#
#  id         :integer          not null, primary key
#  title      :string(255)
#  date       :date
#  time       :string(255)
#  venue      :string(255)
#  speaker    :string(255)
#  details    :text
#  created_at :datetime         not null
#  updated_at :datetime         not null
#

class Event < ActiveRecord::Base
  attr_accessible :date, :details, :speaker, :time, :title, :venue

  validates :date,  presence: true
  validates :time,  presence: true
  validates :title, presence: true
  validates :venue, presence: true
end

app/views/layouts/_sidebar.html.erb:

...
<% Event.all.each do |e| %>
            <li>
              ...
                  <%= link_to e.title, e_path, title: e.title %>
              ...
            </li>
<% end %>

访问出错:

NameError in Menu_pages#about

Showing /.../app/views/layouts/_sidebar.html.erb where line #29 raised:

undefined local variable or method `e_path' for #<#Class:0x007fa71d37fcc8:0x007fa71a5a3a20>

求解... 访问的页面跟 events 分属两个 controller,不知道是不是这个原因,还是别的问题...

你的链接写的不对,如果是要到查看 event 的页面,应该是:

<%= link_to e.title, event_path(e), title: e.title %>

如果是要到编辑 event 的页面,应该是:

<%= link_to e.title, edit_event_path(e), title: e.title %>

#1 楼 @pzgz 额额额,多谢多谢

需要 登录 后方可回复, 如果你还没有账号请 注册新账号