새로운 조인 테이블 "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
는 get_current_user의 않습니다 [: : ID는] 아무것도 반환이 문제를 해결 한 후
, 나는 당신이보기를 리팩토링하는 것이 좋습니다? 조인 된 모델의 has_many : through 연관을 정의 했습니까? – DiegoSalazar
모델에 LastViewer 모델의 'validates : report_id, : person_id, presence : true'를 저장하는 데 두 외래 키가 모두 필요합니다. – MrYoshiji
예, get_current_user [: id]가 올바른 문자열/이름을 반환합니다. 미안해, 두 번째 부분은 무슨 뜻이야? –