Exclude Some Ids from Result in Rails Activerecord

How to exclude an array of ids from query in Rails (using ActiveRecord)?

This should work:

ids_to_exclude = [1,2,3]
items_table = Arel::Table.new(:items)

array_without_excluded_ids = Item.where(items_table[:id].not_in ids_to_exclude)

And it's fully object-oriented with no strings :-)

Exclude some ids from result in Rails ActiveRecord

If Article has_many :sections, try:

Article.find(:all, :joins => :sections, :conditions => ["sections.id IN (?) AND
id NOT IN (?)", [1,2,3], @some_ids], :limit => 4)

How to retrieve and exclude some ids from an ActiveRecord query?

I'm not sure I'm reading your question correctly, but it looks like you just need to collect the alliance user ids:

User.where("ally not in ?", current_user.alliances.collect(&:user_id))

Exclude ID column from ActiveRecord results

select returns Model objects. Your query merely instructs ActiveRecord to restrict the results to include only the number. You can pull whatever data you need from the relation. For example, if you want the numbers as an array, you could do that with:

Phone.select(:number).distinct.where(in_black_list: true).map(&:number)
# => ["1234567", "78567459", ... ]

To avoid having ActiveRecord create model objects, and to request only one column from MySQL, use pluck:

Phone.distinct.where(in_black_list: true).pluck(:number)
# => ["1234567", "78567459", ... ]

How to exclude a collection of records with ActiveRecord?

You could do that:

= select :client, :id, User.where("users.id NOT IN (?)", current_user.manager_users.pluck(:client_id)).map {|u| [u.username, u.id]}, include_blank: "Add a client by username"

The new stuff is here:

User.where("users.id NOT IN (?)", current_user.manager_users.pluck(:client_id))
.map{ |u| [u.username, u.id] }

The current_user.manager_users.pluck(:client_id) part will retrieve (only on the DB-level) all the client_IDs of the manager_users linked to the current_user.

Hope this helps!

How do I exclude search results in ActiveRecord?

find_by doesnt return an active record relation, use where that you can continue to modify:

players = Character.where(your conditions)
players = players.where.not(id: user.id)
# ...

Alternatively you can build a relation, and then call find_by on that relation.

players = Character.where.not(id: user.id)
players = players.where(some other conditions)
# ...
players.find_by(your conditions)

Exclude id in rails scope

Try this:

scope :within_category, ->(category, item_type) { joins(:category).where(:categories => { :id => category }).where(self.arel_table[:id].not_in(item_type.id) }

How to remove id from select active record?

This will give you desired output

User.pluck(:email, :dob)


Related Topics



Leave a reply



Submit