Rails 3/Ruby: Activerecord Find Method in Condition Array to Parameters Single Quote Issue

Rails 3 / Ruby: ActiveRecord Find method IN condition Array to Parameters single quote issue

Answer updated (twice) to reflect Rails 3+ ActiveRecord syntax

Rails 3+

You can use the following syntax:

Post.where(user_id: [1,2,3])

And thus:

Post.where(user_id: args)

Rails 3 or Rails 4 (Original)

For completeness, the Rails 3 syntax would be:

Post.where("user_id IN (?)", [1,2,3]).to_a

If args is an Array, then:

Post.where("user_id IN (?)", args).to_a

Or, if args is an array of strings:

Post.where("user_id IN (?)", args.map(&:to_i)).to_a

The to_a is optional, but will return the results as an array. Hope this helps.

Rails 2

You should be able to simply pass in an array as the parameter, as follows:

find(:all, :conditions => ["user_id IN (?)", [1,2,3] ] )

Thus, if args is an array of ids, you should simply call:

find(:all, :conditions => ["user_id IN (?)", args ] )

In case you have an issues with types, you can do:

find(:all, :conditions => ["user_id IN (?)", args.map { |v| v.to_i } ] )

and this will ensure each item in the array is an Integer.

ActiveRecord where field = ? array of possible values

From here it appears to be done using an SQL in statement:

Model.where('id IN (?)', [array of values])

Or more simply, as kdeisz pointed out (Using Arel to create the SQL query):

Model.where(id: [array of values])

Filter an array with many parameters like an SQL query

select does exactly what you need with as many parameters as you might want:

@usersb.select do |user|
user.need_bedrooms_min >= params[:nb_bedrooms_min].to_i &&
(params[:budget_min].to_i..params[:budget_max].to_i).include? user.budget_amount &&
((params[:surface_min].to_i..params[:surface_max].to_i).include? user.need_surface_min ||
(params[:surface_min].to_i..params[:surface_max].to_i).include? user.need_surface_max)
end

Or, more cleanly:

class User
def needs_apartment?(params)
budget_min, budget_max, surface_min, surface_max, nb_bedrooms_min =
%w{budget_min budget_max surface_min surface_max nb_bedrooms_min}.map{|k| params[k.to_sym].to_i}
budget_range = budget_min..budget_max
surface_range = surface_min..surface_max

need_bedrooms_min >= nb_bedrooms_min &&
budget_range.include? budget_amount &&
(surface_range.include?(need_surface_min) || surface_range.include?(need_surface_max))
end
end

@usersb.select{|user| user.needs_apartment?(params)}

How to get a single column's values into an array

In Rails 3.2 there is a pluck method for this

Just like this:

Person.pluck(:id) # SELECT people.id FROM people
Person.pluck(:role).uniq # unique roles from array of people
Person.distinct.pluck(:role) # SELECT DISTINCT role FROM people SQL
Person.where(:confirmed => true).limit(5).pluck(:id)

Difference between uniq and distinct

Rails using ActiveRecord where when parameter takes an Array

I'd prefer to use Mark's solution, but to make your initial attempt work, you have to change state = ? to state IN (?), like this:

User.where("state IN (?) AND salary >= ?", ["AL", "MI", "MA"], 1000)

This will generate a WHERE ... IN ('...', '...') query, which is what you need when passing an array.

The advantage of using a hash is that Rails automatically generates the correct SQL. It does matter if you pass a string or an array.

How can I make an 'OR' statement in ActiveRecord?

Use the Arel methods to do this:

t = Post.arel_table
ids = [1,2,3]

Post.where(
t[:user].eq("mike").or(t[:channel_id].in(ids))
)

rails query record that must meet all condition

Just a way around solution:

Note: This solution assumes you have no row for two same foreign keys combination like in the following example.

id  | variant_id | option_value_id
22 | 20 | 72
22 | 20 | 72

variant = OptionValueVariant.where(option_value_id: params[:variant][:option_value_ids]).pluck(:variant_id)
variant.select {|i| variant.count(i) == params[:variant][: option_value_ids].uniq.count }.uniq

Ruby on Rails: Is there a method to retrieve an array of data from the database without Rails needing to instantiate anything?

ActiveRecord gives you a direct hook to the current environment database, allowing you execute SQL statements and returning the result in basic structures (arrays or hashes). See: http://ar.rubyonrails.org/classes/ActiveRecord/ConnectionAdapters/DatabaseStatements.html

For example:

ActiveRecord::Base.connection.select_values("SELECT title FROM books")

Will return an array of book titles (strings). This will not instantiate any ActiveRecord instances and will be more memory efficient for your application.



Related Topics



Leave a reply



Submit