2016-08-31 6 views
0

비슷한 문제가 많이 있지만 그 해결책은 없습니다. 나는 관계형 데이터베이스를 가지고있다. 특히 저는 서로 관련있는 두 개의 테이블을 가지고 있습니다 : 프로그램과 강사.Ruby on Rails : 정의되지 않은 메소드 'instructors'for nil : NilClass

프로그램 "has_many : 강사"

테이블 사이의 관계는 다음과 와 "belongs_to : 프로그램"강사 :

여기

이 테이블 '모델의 코드는

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 
을3210

상기 제어기는 :

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을?" 다음 오류와 함께 실패 : 정의되지 않은 메서드`instructors 'for nil : NilClass

나는 왜 도움이되지 않습니다 모르겠다.

답변

0

이 문제는 관계에 의해 반드시 야기 된 것은 아니지만 @an 변수가 nil이라는 사실로 인해 해당 약어가있는 레코드가 없음을 나타냅니다. 아마도, 사용하기 전에 @an (또는 다른 것들)이 nil인지 여부에 대한 확인을 시도해보십시오.

+0

고맙습니다! 이것은 문제를 해결했습니다! –

관련 문제