1
我有這些模型類:與HAS_ONE多態關聯不起作用
class Song < ActiveRecord::Base
has_many :urls, as: :media
has_one :url, as: :media
end
class Url < ActiveRecord::Base
belongs_to :media, polymorphic: true
end
奇怪這裏的是,Song.first.url
總是返回零,但Song.first.urls
返回的URL列表。
這裏是生成的SQL查詢:
Song.includes(:url).first.url # => nil
Song Load (0.4ms) SELECT `songs`.* FROM `songs` LIMIT 1
Url Load (0.4ms) SELECT `urls`.* FROM `urls` WHERE `urls`.`media_type` = 'Song' AND `urls`.`media_id` IN (1)
Song.includes(:urls).first.urls # => [list of urls]
Song Load (0.7ms) SELECT `songs`.* FROM `songs` LIMIT 1
Url Load (0.5ms) SELECT `urls`.* FROM `urls` WHERE `urls`.`media_type` = 'Song' AND `urls`.`media_id` IN (1)
我運行軌道3.2.0.rc2關於Ruby 1.9.2
任何爲什麼會這樣的想法?
這很有趣:-) – 2012-01-05 16:00:57
確實如此。我不知道它是否是一個bug ... – Oleander 2012-01-05 16:08:26
如果從模型中刪除has_many,該怎麼辦?如果你做'Song.includes(:url,:url).first.url',會怎麼樣? – 2012-01-05 16:09:14