私のアプリに教師の記録をリストしようとしています。私は教師を読み込むときに読み込まれていない入れ子のPolymorphic Contactオブジェクト(これはStudentsと共有されています)を持っています。Nailsを返すネストされたオブジェクトをレンダリングする
def index
@teachers = Teacher.all.includes(:contact)
end
をし、それをリストアップ:
class Teacher < ApplicationRecord
has_one :contact, as: :contactable
has_many :groups
has_many :students, through: :groups
validates :instrument, presence: true
accepts_nested_attributes_for :contact, allow_destroy: true
end
class Contact < ApplicationRecord
belongs_to :contactable, polymorphic: true
belongs_to :teacher, foreign_type: 'Teacher', foreign_key: 'contactable_id', required: true
validates :first_name, presence: true
validates :last_name, presence: true
validates :email, presence: true
end
私はインデックスメソッドでは、すべての教師を読み込む:
は、ここでのオブジェクトです
<% @teachers.each do |teacher| %>
<tr>
<td>
<%= teacher.contact.username %>
</td>
<td>
<%= teacher.contact.email %>
</td>
<td>
<%= teacher.contact.first_name %>
</td>
<td>
<%= teacher.contact.last_name %>
</td>
<td>
<%= teacher.instrument %>
</td>
<td>
<%= link_to 'Show', teacher_path(teacher) %>
</td>
<td>
<%= link_to 'Edit', edit_teacher_path(teacher) %>
</td>
<td>
<%= link_to 'Destroy', teacher_path(teacher),
method: :delete,
data: { confirm: 'Are you sure?' } %>
</td>
</tr>
<% end %>
しかし、私は次のエラーを取得しますa:
undefined method `username' for nil:NilClass
<tr>
<td>
<%= teacher.contact.username %>
基本的に連絡先は空です。私は各教師のためにそれをロードすると思うあらゆる方法を試しましたが、何も動作しません。レコードはDBにあり、正しいです:
Teacher Load (1.2ms) SELECT "teachers".* FROM "teachers"
=> #<ActiveRecord::Relation [#<Teacher id: 1, instrument: "Piano", created_at: "2017-03-14 18:04:30", updated_at: "2017-03-14 18:04:30">, #<Teacher id: 2, instrument: "Pia
no", created_at: "2017-03-14 18:04:52", updated_at: "2017-03-14 18:04:52">]>
2.4.0 :005 > Contact.all
Contact Load (0.2ms) SELECT "contacts".* FROM "contacts"
=> #<ActiveRecord::Relation [#<Contact id: 1, username: "ericklind", first_name: "Erick", last_name: "Lind", email: "[email protected]", contactable_type: "Teacher", con
tactable_id: 2, created_at: "2017-03-14 18:04:52", updated_at: "2017-03-14 18:04:52">]>
また、クエリがレコードを選択しているので、彼らはそこにする必要があります:
Started GET "/teachers" for ::1 at 2017-03-16 09:46:57 -0700
Processing by TeachersController#index as HTML
Teacher Load (0.1ms) SELECT "teachers".* FROM "teachers"
Contact Load (0.1ms) SELECT "contacts".* FROM "contacts" WHERE "contacts"."contactable_type" = ? AND "contacts"."contactable_id" IN (1, 2) [["contactable_type", "Teacher"]]
ありがとう!
私はそれと関連があるかもしれません '' ' belongs_to:teacher、foreign_type: '教師'、foreign_key: 'contactable_id'、必須:tru e '' ' これはポリモーフィックなので、アソシエーションを2回指定する必要はありません。おそらく、それは協会の決議者を駄目にするかもしれない。 –