【问题标题】:Ruby on Rails : undefined method `instructors' for nil:NilClassRuby on Rails:nil:NilClass 的未定义方法`instructors'
【发布时间】:2016-08-31 18:07:57
【问题描述】:

我知道有很多类似的问题,但这些解决方案都不起作用。我有一个关系数据库。具体来说,我有两个相互关联的表:程序和讲师。

表之间的关系如下:

一个程序“has_many :instructors” 和一个讲师“belongs_to :program”

这是表格模型的代码:

class Program < ActiveRecord::Base
  validates_presence_of :slug

  has_many :instructors
  has_many :degrees
  has_many :disciplines
  has_many :projects
  has_many :articles

  def to_param
    slug
  end
end

class Instructor < ActiveRecord::Base
  belongs_to :program

  has_attached_file :portrait,
    :storage => :s3,
    :path => "/pictures/:id/:filename"

  # has_attached_file :featured_picture
  validates_attachment_content_type :portrait, content_type: /\Aimage\/.*\Z/

end

我也有一个很简单的看法:

= render('layouts/menu')
 .infra-centered
  = render('navigation')
  .infra-row
.infra-col-12
  %h2 Animation
  -if @an.instructors.empty?
    %p.notes Add faculty
  - else
    %table
      %tr
        %th Name
        %th Position
        %th Office
        %th Phone
        %th Email
      - @an.instructors.order(:lastname).each do |instructor|
        %tr
          %td= instructor.firstname + " " + instructor.lastname
          %td= instructor.rank
          %td= instructor.office
          %td= instructor.phone
          %td= instructor.email

控制器是:

class PagesController < ApplicationController
  def contacts
    @employees = Employee.all
    @an = Program.where(abbreviation: "an").first
    @gd = Program.where(abbreviation: "gd").first
    @il = Program.where(abbreviation: 'il').first
    @ph = Program.where(abbreviation: 'ph').first
  end
end

问题是 RoR 没有识别表之间的关系,导致出现“@an.instructors.empty?”行失败并出现以下错误:nil:NilClass 的未定义方法 `instructors'

我不知道为什么不工作请帮忙。

【问题讨论】:

    标签: ruby-on-rails relational-database


    【解决方案1】:

    问题不一定是关系造成的,而是@an变量为nil,说明没有找到该缩写的记录。也许,在尝试使用它们之前,尝试在您的视图中检查 @an(或其他)是否为 nil。

    【讨论】:

      猜你喜欢
      • 1970-01-01
      • 2012-09-24
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      • 2014-09-21
      • 1970-01-01
      • 1970-01-01
      • 2016-12-15
      相关资源
      最近更新 更多