2014-02-20 5 views
1

새로운 조인 테이블 "LastViewer"를 생성하여 두 개의 기존 테이블 "Report"와 "Person"을 조인하려고합니다. 기본적으로 Viewer 표는 마지막으로 보고서를 본 사람을 추적합니다. 이것은 다음과 같은 마이그레이션 발생Rails 모델/조인 테이블이 제대로 작동하지 않습니다.

class LastViewer < ActiveRecord::Base 
    belongs_to :report 
    belongs_to :person 
end 

:

내가 이런 "last_viewer.rb"파일을 작성하여 레일 모델을 만들어 지금

class CreateLastViewers < ActiveRecord::Migration 
    def change 
    create_table :last_viewers do |t| 
     t.references :person 
     t.references :report 

     t.timestamps 
    end 
    add_index :last_viewers, :person_id 
    add_index :last_viewers, :report_id 
    end 
end 

을, 나는 코드를 추가 시작 있도록 내 앱이 변경 사항을 추적합니다. 나는 올바른 컨트롤러에 다음과 같은 추가 : 내가 마지막 뷰어를 표시하고 싶었보기에, 지금

@viewer = LastViewer.new 
@viewer.person_id = get_current_user[:id] # correctly gets the person's ID from the correct session 
@viewer.report_id = @report.id 
@viewer.save 

을 그리고를, 내가 추가 :

<% @reports.each_with_index do |report,index| %> 
    <% query = LastViewer.where(:report_id => report.id).last %> 
    <% name = query.person.name || "No Person found" %> 
    <% time = Format.to_time(query.created_at.localtime) %> 
<% end %> 

을 내가 오류는 다음과 같습니다

무 대한 정의에있어서 '이름'NilClass

라인에

<% name = query.person.name || "No Person found" % 

편집 :

인격 모델의 각각의 부분 :

class Person< ActiveRecord::Base 
    attr_accessible :hid, :name, :email, :cell, :display 
    has_many :last_viewer 
end 

보고서 모델의 각각의 부분 :

class Report< ActiveRecord::Base 
    has_many :last_viewer 
end 
+0

는 get_current_user의 않습니다 [: : ID는] 아무것도 반환이 문제를 해결 한 후

, 나는 당신이보기를 리팩토링하는 것이 좋습니다? 조인 된 모델의 has_many : through 연관을 정의 했습니까? – DiegoSalazar

+0

모델에 LastViewer 모델의 'validates : report_id, : person_id, presence : true'를 저장하는 데 두 외래 키가 모두 필요합니다. – MrYoshiji

+0

예, get_current_user [: id]가 올바른 문자열/이름을 반환합니다. 미안해, 두 번째 부분은 무슨 뜻이야? –

답변

1

먼저,이에 관계를 변경해야합니다 : 당신은 오류 방지하기 위해 try를 사용할 수있는 다음 (has_many :last_viewers에 복수)

class Person < ActiveRecord::Base 
    has_many :last_viewers 


class Report < ActiveRecord::Base 
    has_many :last_viewers 

class LastViewer < ActiveRecord::Base 
    belongs_to :report 
    belongs_to :person 
    validates :report_id, :person_id, presence: true 

을의 LastViewer 객체의 생성을 강제로 시도 오류를 높이고 개체 뭐가 잘못 볼 수 있습니다 :

@viewer = LastViewer.new 
@viewer.person_id = get_current_user[:id] 
@viewer.report_id = @report.id 
@viewer.save! # adding a ! will raise errors if object not valid 

# one-line equivalent: 
@viewer = LastViewer.create!(person_id: get_current_user[:id], report_id: @report.id) 

나는 같은 오류가 "person_id로는 비어 있어야되지 않는다"것입니다 확신합니다. 귀하의 방법 get_current_user[:id]이 이드를 반환하지 않는다고 생각합니다.

<% @reports.each_with_index do |report, index| %> 
    <% last_viewer = report.last_viewers.last %> 
    <% last_person_name = last_viewer.try(:person).try(:name) %> 
    <% time = Format.to_time(query.created_at.localtime) %> 
<% end %> 
+0

당신은 get_current_user [: id]가 id 대신에 그 사람의 hid를 반환 한 것에 대해 정확했습니다. 이제 Person 테이블에서 hid = get_current_user [: id]를 검색 한 다음 결과 사용자의 ID를 가져올 때 작동합니다. 정말 고마워요, 당신의 의견은 사건에 금이갔습니다! :) –

2

query.person이 전무하다.

<% name = query.person.try(:name) || "No Person found" %> 
+0

오류가 수정되었지만 지금은 "사람을 찾지 못했습니다"(간단히 말해서와 같이)를 인쇄합니다.다른 잠재적 인 오류가 보이십니까? 이것은 처음으로 테이블을 조인하므로 내가 올바르게했다는 확신이 없다. –

+1

다른 사람들처럼'get_current_user [: id]'는 반환해야한다고 생각하는 ID를 반환하지 않을 가능성이 높습니다. 'Person' 객체에서 기본 키 ('id')를 반환해야합니다. –

+0

죄송 합니다만 기본 키 id는 Person 테이블에있는 해당 Person의 색인 ID를 의미합니까? –

관련 문제