【问题标题】:How to create a conditional and chainable query method如何创建条件和可链接的查询方法
【发布时间】:2015-10-28 12:31:42
【问题描述】:

我有三个模型:PostCommentUser

在评论帖子时,用户可以选择“仅为帖子作者显示”并且Comment 属性public 获得false 值。

如果私有 cmets 属于 current_user 或者是帖子作者正在查询,则该方法应该只返回它们。

我将如何构造条件@9​​87654328@ 方法以及它应该使用哪个模型?

post.ordered_comments.exclude_unauthorized_privates

【问题讨论】:

  • 您是否在为您的 cmets 使用 gem,acts_as_commentable
  • 不,我不是,我对创建带有条件的查询的一般想法很感兴趣。

标签: ruby-on-rails ruby-on-rails-4 rails-activerecord


【解决方案1】:

我会这样做。

在您的 Post 模型上,我会创建一个这样的方法:

def is_author?
  current_user.id == user_id
end

这将允许您检查页面上的current_user 是否是帖子的作者。

然后在您的 Comment 模型上添加此范围:

scope :public, lambda { |user_id|
  where("user_id = ? OR public = ?", user_id, 1)
} 

然后为了让 cmets 从您的控制器显示在页面上,我会将您的 @comments 设置为:

@comments = post.is_author? post.ordered_comments : post.ordered_comments.public(current_user.id)

这会将@comments 变量传递给您的视图,您将只看到应该显示给current_user 的cmets。

【讨论】:

  • 这允许 current_user 查看所有私人 cmets(不仅仅是她自己的)。
  • is_author 上的 user_id?是 db 中为 belongs_to 关系列出的 id。这将允许帖子作者看到所有 cmets,而所有其他人看不到私人 cmets。
  • 是的,每个commet都有一个user_id。澄清一下:帖子作者应该看到所有的 cmets。普通用户不应该看到除自己以外的任何私人 cmets。
  • 啊,好吧。我更新了答案以反映普通用户应该仍然可以看到自己的私人 cmets。
【解决方案2】:

首先让我说 post 应该只有一种方法,否则就是违反 demeter 的。只需将委托 :ordered_authorized_cmets 发布到 cmets。

我认为您应该为此使用arel。我认为查询需要类似于“where private: true or user: [poster, commentor]”(语法正确除外)。使用 arel 实现 OR 比使用丑陋的 sql 语句更容易。当然是你的选择。

【讨论】:

    猜你喜欢
    • 1970-01-01
    • 2023-03-13
    • 2015-10-07
    • 1970-01-01
    • 2011-09-07
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    相关资源
    最近更新 更多