[英]Retrieve polymorphic associations in Rails from one model
class User < ActiveRecord::Base
has_many :posts
has_many :images, as: :imageable
end
class Post < ActiveRecord::Base
belongs_to :user
has_many :images, as: :imageable
end
class Image < ActiveRecord::Base
belongs_to :imageable, polymorphic: true
end
有沒有一種特定的方法可以執行User.images並獲取用戶圖像和屬於該用戶的帖子圖像?
由於某種原因,我無法全力以赴地做到最好。
在這種情況下,您可以避免多態關系,簡單的has_many
和belongs_to
就足夠了。 在哪里:
class User ActiveRecord::Base
has_many :posts
has_many :images
end
class Post ActiveRecord::Base
belongs_to :user
has_many :images
end
class Image < ActiveRecord::Base
belongs_to :post
belongs_to :user
end
但是話又說回來,我想您想問的是User.last.images
而不是User.images
同樣可以通過has_many通過關聯來完成
聲明:本站的技術帖子網頁,遵循CC BY-SA 4.0協議,如果您需要轉載,請注明本站網址或者原文地址。任何問題請咨詢:yoyou2525@163.com.