RoR 通过加入、选择和订购过滤掉当前用户 [英] RoR Filter Out Current User with Join, Select and Order

查看:49
本文介绍了RoR 通过加入、选择和订购过滤掉当前用户的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

我在名为提名的 RoR 控制器中有以下声明:

I have the following statement in an RoR controller called nominations:

@users = User.joins(:department).select("CONCAT(last_name, ', ', first_name, 
   ' - ', name) as user_dept, last_name, first_name, name, 
   users.id").order("last_name, first_name, middle_name")

在视图中,我可以将其放在下拉列表中:

In the view, I have this to put this in a drop down:

<%= select_tag "nomination[user_id]", options_from_collection_for_select(@users, 
     :id, :user_dept), prompt: "Select User" %>

我想过滤掉当前用户,这样别人就不能提名自己了.我看过几篇关于使用 where.not 或 scope (例如) 但我能找到的所有语句都是从一张表中选择的基本选项.如何在保留所有其他内容的同时定义和使用范围?我需要那个连接和格式.

I want to filter out the current user so that someone can't nominate themselves. I've seen several articles about using where.not or scope (for example) but all of the statements I could find are basic selections from one table. How do I define and use a scope while preserving all of the other stuff? I need that join and formatting.

编辑 - 每当我在控制器或模型中的任何地方尝试 where.not 时,我都会收到错误参数数量错误(0 代表 1)".

Edit - Whenever I try where.not anywhere in the controller or model, I get the error "wrong number of arguments (0 for 1)".

推荐答案

这应该可以解决问题:

@users = ...
@users = @users.where.not(users: {id: current_user.id})

请注意,在进行连接时,您需要指定表的名称(而不是模型),否则数据库将不知道它应该查找哪个 id 列(users.id vs departments.id).

Note that you need to specify name of the table (not the model) when you do the join, otherwise database will have no idea which id column it should look for (users.id vs departments.id).

not 方法是一个很新的东西,在 Rails 3 中不可用.(事实上,方法不期望在没有参数的情况下被调用,这就是为什么你得到的错误是 意外数量的参数(0 代表 1)).

not method is quite a new thing and is not available in Rails 3. (In fact, where method wasn't expecting to be called without arguments, that's why the error you got is unexpected number of arguments (0 for 1)).

那是一段黑暗时期,我们不得不使用以下怪物来使工作正常进行:

Those were dark times when we had to use the following monstrosity to get stuff working:

@users = ...
@users = @users.where('users.id != ?', current_user.id)

这篇关于RoR 通过加入、选择和订购过滤掉当前用户的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆