[英]Ruby on Rails: Polymorphic Association Confusion
我正在GitHub上的ruby on rails應用程序之一中遇到以下情況:
我有以下要轉換為多態的模型:
class Comment < ActiveRecord::Base
belongs_to :team
belongs_to :user
belongs_to :application
belongs_to :project
end
class Team < ActiveRecord::Base
has_many :comments
end
class Project < ActiveRecord::Base
has_many :comments, -> { order('created_at DESC') }, dependent: :destroy
end
class User < ActiveRecord::Base
end
class Application < Rails::Application
end
我進行了以下更改以使其具有多態性:
對已刪除的team_id
, project_id
, application_id
和user_id
進行數據庫更改,並將commentable_id
和commentable_type
添加到comments
表。
在rails指南中描述的模型修改:
class Comment < ActiveRecord::Base
belongs_to :commentable, polymorphic: true
end
class Team < ActiveRecord::Base
has_many :comments, as: :commentable
end
class Project < ActiveRecord::Base
has_many :comments, as: :commentable, -> { order('created_at DESC') }, dependent: :destroy
end
當我將其與默認范圍一起使用時,它不允許我與默認范圍一起使用,並在以下行中給出錯誤:
has_many :comments, as: :commentable, -> { order('created_at DESC') }, dependent: :destroy
我很困惑要更改以下模型:
class User < ActiveRecord::Base
end
class Application < ActiveRecord::Base
end
我需要對User
和Application
模型進行以下更改嗎?
class User < ActiveRecord::Base
has_many :comments, as: :commentable
end
class Application < ActiveRecord::Base
has_many :comments, as: :commentable
end
提前致謝!
如果您的用戶/應用程序對象需要注釋,則添加
class User < ActiveRecord::Base
has_many :comments, as: :commentable
end
class Application < ActiveRecord::Base
has_many :comments, as: :commentable
end
否則創建不是多態的Eg的屬屬關系。
class User < ActiveRecord::Base
has_many :comments
end
class Application < ActiveRecord::Base
has_many :comments
end
聲明:本站的技術帖子網頁,遵循CC BY-SA 4.0協議,如果您需要轉載,請注明本站網址或者原文地址。任何問題請咨詢:yoyou2525@163.com.