Quantico
Quantico

Reputation: 2446

excluding a value from a form drop down in rails

I have a form drop down, that shows me all the emails in my User db table.

  <%= f.collection_select(:accessor_id, User.all,:email ,:email) %>

I want to exclude from this list the value of the current's user email, which I can find with with current_user.email (already defined and working)

I know I can achieve this via the following query:

  <%= f.collection_select(:accessor_id, User.select(:email).where("email !=?" , current_user.email),:email ,:email) %>

i wanted to know if it is possible to do this after User.all returned all of the values.

Upvotes: 0

Views: 879

Answers (2)

phoet
phoet

Reputation: 18845

you mean something like

User.all.reject {|user| user == current_user}

or more precisely i would fetch all users somewhere in the controller

def index
  @users = User.all
end

and use something like that in the form

<%= f.collection_select(:accessor_id, @users.reject {|user| user == current_user}.map(&:email)) %>

Upvotes: 3

house9
house9

Reputation: 20624

@phoet answer is correct, personally I would probably do this at database level anyhow, something along lines of

class User < ActiveRecord::Base
  # ...

  def self.all_without(excluded)
    where("id NOT IN (?)", excluded)
  end
end


<%= f.collection_select(:accessor_id, User.all_without([current_user]), :email ,:email) %>

try to keep the view 'clean' of the details, if possible

# and if you really do only want to pull email from the database, you can chain the query
User.all_without([current_user]).select(:email)

Upvotes: 3

Related Questions