Rails 5包括和多态

时间:2017-02-15 17:15:30

标签: ruby-on-rails rails-activerecord ruby-on-rails-5 polymorphic-associations

我使用Rails 5并尝试做下一步

class Song
  has_and_belongs_to_many :artists
end

class UnknownSong
end

class Library
  belongs_to :media, polymorphic: true

  belongs_to :song, foreign_key: :media_id, foreign_type: :media_type
  belongs_to :unknown_song, foreign_key: :media_id, foreign_type: :media_type
end

当我运行此查询时

Library.includes(song: [:artists], :unknown_song)

rails生成下一个sql

SELECT "songs".* FROM "songs" WHERE "songs"."id" IN (391497, 921, 1469, 172)
SELECT "unknown_songs".* FROM "unknown_songs" WHERE "unknown_songs"."id" IN (391497, 921, 1469, 172)

并尝试使用相同的ID加载不同的多态模型

data in database

enter image description here

如何解决这个问题?

0 个答案:

没有答案