0

사용자 당 사용자 수를 하나만 갖게하고 싶습니다. 그러나 나는 "nil : NilClass"에 대한 "undefined method`matriculation '오류가 발생합니다. 내가 어떻게 작동시킬 수 있니? (나는 사안 인 경우 사용자 인증으로 고안합니다). has_one 협회사용자 당 게시물 1 개로 제한 작성

def matriculation_limit 
    if self.user.matriculations(:reload).count <= 1 
    errors.add(:base, "Yuo already have one matriculation form") 
    else 
    redirect_to new_matriculation_path 
    end 
end 
+0

는 "current_user.matriculations.build"(또는 비슷한)를 사용하여 컨트롤러의 관계를 구축 할 것입니다 당신은 has_one을 가지고, 그래서 당신은 사용할 수 있나요? 편집 작업에서 편집하십시오. – dodgerogers747

+0

내가하지는 않았지만 그것을 구축하려고합니다. –

+0

이 오류 메시지는 'self.user'가 nil이라는 것을 나타냅니다. 왜 그런지 파악하고 문제를 해결하는 길에 서 있습니다. –

답변

1

후 연관 파인더 방법 @user.matriculation하지 @user.matriculations 같은 단수이다. 그리고 거기에는 오직 하나만있을 것이므로 아무런 요점도 없습니다. 그것이 유일한 연결이기 때문에 그냥 외래 키 열에서 ID를 변경 협회 (업데이트됩니다, 그래서 당신은, 사용자가 가지고 어디 얼마나 많은 matriculations 확인 할 필요가 없습니다

: 코멘트에 대해서는

users 테이블에 matriculation_id)

class User < ActiveRecord::Base 
    has_one :matriculation, :class_name => "User", :foreign_key => "matriculation_id" 
end 

class Matriculation < ActiveRecord::Base 
    belongs_to :user 
end 

# some controller action... 
    @user.matriculation = Matriculation.find(params[:matriculation_id]) # or something! 
+0

작성 또는 업데이트 작업을 올바르게 시도하지 못했습니다. "ID없이 입학을 찾을 수 없습니다"라는 오류가 나타납니다. ID를 찾을 수 없으므로 nil을 반환합니다! ID를 표시하는 방법을 거의 이해하지 못했습니다! –

0

self.user == user_object.user. 그리고 클래스 사용자를위한 메소드 사용자가 없다고 생각됩니다. 다른 것들, self.matriculation

그래서 올바른

if self.matriculation 
    errors.add(:base, "Yuo already have one matriculation form") 
    else 
    redirect_to new_matriculation_path 
    end 
+0

'self.matriculation.count'는 Matriculation 오브젝트가 리턴되고'count' 메소드가 없으므로 예외가 발생합니다. –

+0

예, has_one 관계를 잊어 버렸습니다. 고정 코드 – Avdept