has_one :通过多态 - 这可能吗?
我的应用程序中有模型:
class Comment < ActiveRecord::Base
belongs_to :commentable, :polymorphic => true
端
类 Project < ActiveRecord::Base
has_many :discussions, :dependent => :destroy
has_many :tickets, :dependent => :destroy
端
类讨论 < ActiveRecord::Base
has_many :comments, :as => :commentable, :dependent => :destroy
端
类 Ticket < ActiveRecord::Base
has_many :comments, :as => :commentable, :dependent => :destroy
end
一切正常,但有时通过commentable从comment中获取项目不太方便,即comment.commentable.project。 有没有办法在Comment模型中制作has_one项目?
I have models in my app:
class Comment < ActiveRecord::Base
belongs_to :commentable, :polymorphic => true
end
class Project < ActiveRecord::Base
has_many :discussions, :dependent => :destroy
has_many :tickets, :dependent => :destroy
end
class Discussion < ActiveRecord::Base
has_many :comments, :as => :commentable, :dependent => :destroy
end
class Ticket < ActiveRecord::Base
has_many :comments, :as => :commentable, :dependent => :destroy
end
Everything works fine, but sometimes it's not very convinient to get project from comment through commentable, i.e. comment.commentable.project.
Is there any way to make has_one project in Comment model?
如果你对这篇内容有疑问,欢迎到本站社区发帖提问 参与讨论,获取更多帮助,或者扫码二维码加入 Web 技术交流群。
绑定邮箱获取回复消息
由于您还没有绑定你的真实邮箱,如果其他用户或者作者回复了您的评论,将不能在第一时间通知您!
发布评论
评论(1)
我会将以下方法添加到您的类
Comment
中:这将为您提供相同的结果,而无需使用
ActivRecord
的所有魔力。I would add the following method to your class
Comment
:This will give you the same result without all the magic of
ActivRecord
.