【问题标题】:Polymorphic association with condition与条件的多态关联
【发布时间】:2020-07-16 14:21:13
【问题描述】:

我们有以下型号...

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

无法达到我的预期..,请在此处提供帮助...

【问题讨论】:

    标签: ruby-on-rails-4 associations


    【解决方案1】:

    我喜欢你的方法

    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
    

    希望,它会有所帮助。

    【讨论】:

    • 这实际上并不能解决问题。当我做Comment4.post你可以看到查询SELECT `posts`.* FROM `posts` INNER JOIN `comments` ON `comments`.`commentable_id` = `posts`.`id` AND `comments`.`commentable_type` = 'Post' WHERE `posts`.`id` = '2' AND `comments`.`commentable_type` = 'Post' LIMIT 1
    • 它返回了一个对象而不是nil
    • @RAJASHARMA,我已经更新了我的答案,现在请检查。
    猜你喜欢
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 2014-07-08
    • 1970-01-01
    • 1970-01-01
    相关资源
    最近更新 更多