问题
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" %>
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.
Edit - Whenever I try where.not anywhere in the controller or model, I get the error "wrong number of arguments (0 for 1)".
回答1:
This should do the trick:
@users = ...
@users = @users.where.not(users: {id: current_user.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
).
Before Rails 4
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)
回答2:
You need a scope in the User
model:
class User < ActiveRecord::Base
scope :except_id, -> (id) ( where.not(id: id) )
end
Then you can freely use it everywhere you want:
@users = User.except_id(current_user.id).joins(:department).select("...")
回答3:
@users = User.where.not(id: current_user.id).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")
来源:https://stackoverflow.com/questions/31748834/ror-filter-out-current-user-with-join-select-and-order