[英]Rails polymorphic comments associate
嘗試建立一個多態關聯,其中“注釋”可以屬於“照片和用戶”。 將對用戶的評論視為“直接消息”。 但是我把用戶關聯弄得一團糟。
class Comment < ActiveRecord::Base
belongs_to :commentable, polymorphic: true
end
class Photo < ActiveRecord::Base
has_many :comments, as: :commentable, dependent: :destroy
end
class User < ActiveRecord::Base
has_many :comments, dependent: :destroy
has_many :messages, as: :commentable
end
這是不正確的。 理想情況下, user.comments
應該在user_id == user.id
情況下檢索所有Comment記錄,而user.messages
應該在類型為User
且它們是主題的情況下檢索所有Comment記錄。
關系:
class Comment < ActiveRecord::Base
belongs_to :commentable, polymorphic: true
belongs_to :user
end
class Photo < ActiveRecord::Base
has_many :comments, as: :commentable, dependent: :destroy
end
class User < ActiveRecord::Base
has_many :comments, dependent: :destroy
has_many :messages, as: :commentable, class_name: 'Comment'
end
架構:
# Comments
...
t.integer :user_id
t.integer :commentable_id
t.string :commentable_type
...
然后,您可以調用:
@user.comments # Get all comments created by particular user
@user.messages # Get all comments where particular user is a subject
您是否已在comments
表中添加了外鍵和類型列? 在遷移文件中:
def change
add_column :comments, :commentable_type, :integer
add_column, :commentable_type, :string
add_index :comments, [:commentable_type, :commentable_id]
end
還要確保您有一個Message
模型並且它具有關聯
class Message < ActiveRecord::Base
has_many :comments, dependent: :destroy
belongs_to :commentable, polymorphic: true
end
聲明:本站的技術帖子網頁,遵循CC BY-SA 4.0協議,如果您需要轉載,請注明本站網址或者原文地址。任何問題請咨詢:yoyou2525@163.com.