ruby-on-rails-4 - 与条件的多态关联
问题描述
我们有以下型号...
class Post
has_many: :comments, as: :commentable
end
class Media
has_many: :comments, as: :commentable
end
class Comment
belongs_to: :commentable, polymorphic: true
belongs_to: :post, foreign_key::post_id, foreign_type: 'Post'
end
示例
Post1 has Comment3 => {id: 3, text: "Some comment 3", commentable_id: 1, commentable_type: 'Post'}
Media2 has Comment4 => {id: 4, text: "Some comment 4", commentable_id: 2, commentable_type: 'Media'}
When I want to access Comment3.post it gives result as expected.
But When some how want access Comment4.post it brings an object from post table which has id = 2, but expected nil, coz Comment4 does not belongs to any post.
我们可以从 Comment 模型中的以下方法获取,但希望作为关联。
def post
self.commentable if self.commentable_type == 'Post'
end
无法达到我的预期..,请在此处提供帮助...
解决方案
我喜欢你的方法
def post
self.commentable if self.commentable_type == 'Post'
end
但是如果你真的需要关联方式,那么你可以试试
belongs_to :post, foreign_key: :commentable_id, foreign_type: :commentable_type, polymorphic: true
或者
belongs_to :post, -> (record){ record.commentable_type == 'Post' ? joins(:comments).where(comments: {commentable_type: 'Post'}) : where("false") }, foreign_key: :commentable_id
希望能帮助到你。
推荐阅读
- hibernate - Hibernate:如何将数据保存在复合键中,其中一个列具有一对多关系但其他列没有使用 IDClass?
- java - Apache POI:无法更改单元格值
- java - 以编程方式更改 Android 中的模拟色彩空间和其他开发人员选项(已解决)
- java - 在查询期间不要解析 @ManyToOne 字段
- .net - 如何确定是否确实需要滚动到元素?
- javascript - 将脚本从正文移动到头部
- php - $var = array($key => array()) VS $var[] = array($key => array()) 之间的区别
- html - CSS 文件不会在 React JS 中加载
- javascript - 如何设置对象数组中的项目
- html - 如何阻止对静态站点的访问?