Rails4:UsersController中的NoMethodError #show,undefined method

时间:2016-03-12 08:56:01

标签: ruby-on-rails ruby ruby-on-rails-4 ruby-on-rails-4.2

我想开发一个应用程序。 每个用户都创建自己的日程安排。

我想将数据显示如下;

schedule title (user name)

  day1(mm/dd,yyyy)
    09:00 Math
    11:00 Science
    Room name A

  day2(mm/dd,yyyy)
    10:00 Physics 
    13:00 Music
    Room name B

如何在活动模型中显示课程信息?

e.g。标题(数学,科学),时间(从,到)......

当我尝试显示页面时出现以下错误。

NoMethodError (undefined method `event' for #<Room:0x007fb2149a1ac8>
Did you mean?  events
           events=):
  app/views/schedules/_schedule.html.erb:6:in `block in _app_views_schedules__schedule_html_erb___2809280481749604534_70201410929300'
  app/views/schedules/_schedule.html.erb:4:in `_app_views_schedules__schedule_html_erb___2809280481749604534_70201410929300'
  app/views/users/show.html.erb:11:in `_app_views_users_show_html_erb__1629176981125983348_70201561746560'

如果你能给我任何建议,我将不胜感激。

user.rb

class User < ActiveRecord::Base
  has_many :schedlues
  has_many :rooms, through: :schedules
  ...

schedule.rb

class Schedule < ActiveRecord::Base
  belongs_to :user
  has_many :rooms
  ...

room.rb

class Room < ActiveRecord::Base
  belongs_to :schedlue
  has_many :events

event.rb

class Event < ActiveRecord::Base
  belongs_to :room

(虽然我认为'房间has_many事件'不合适,但我不知道。)

模式

create_table "users", force: :cascade do |t|
    t.string   "name"
    t.string   "email"
    ...
end

create_table "schedules", force: :cascade do |t|
    t.string   "title"
    t.integer  "user_id"
    ...
end

create_table "rooms", force: :cascade do |t|
    t.date     "date"
    t.string   "room_name"
    t.integer  "schedule_id"
    ...
end

create_table "events", force: :cascade do |t|
  t.time     "from"
  t.time     "to"
  t.string   "title"
    ...
end

users_controller.rb

class UsersController < ApplicationController
  def show
    @user = User.find(params[:id])
    @schedules = @user.schedules.paginate(page: params[:page])
  end
  ...

show.html.erb

    <% if @user.schedules.any? %>
      <ol class="schedules">
        <%= render @schedules %>
      </ol>
      <%= will_paginate @schedules %>
    <% end %>

_schedule.html.erb

<li>
  <p>
  <% schedule.room.each do |a| %>
    <p><b>Day <%= a.day %></b></p>
    <% a.event.each do |e| %>  #error occur
      <% if e.title.any? %>
        <%= e.title %>
      <% end %>
    <% end %>
    <p>room: <%= a.room_name %></p>
  <% end %>
  </p>
</li>

1 个答案:

答案 0 :(得分:0)

如错误消息所述,Room没有方法event。原因是在您的模型中,您有has_many :events,它会为您提供Association而不是单个事件。所以试试:

room.events.first 

或类似

room.events.each do |event|
  puts event
end

这应该可以解决您现在遇到的错误。

编辑我忘记查看您的模板了。以下行错误:

<% a.event.each do |e| %>

如上所述,解决方案是:

<% a.events.each do |e| %>

有趣的是,你没有在schedule.room上收到错误。这也是错误的,它必须是schedule.rooms