Rails: rewrite a find_all_by() with a .where method - ruby-on-rails

I'm using a gem that doesnt work on the arrays from the find_all_by() method, but does with the .where(); however, I don't know how to write it in a way that produces the same result.
For instance, how could I rewrite:
Post.find_all_by_poster(#user.id , :conditions => ['title IS NOT NULL OR name !=?', 'Bob' ])
My attempt:
Post.where("poster = ? AND title !=? OR name !=?", #user.id, 'NULL', 'Bob')
Any ideas? I'm having trouble satisfying the same conditions. Thanks for your help!

You still need to use IS NOT NULL instead of passing in NULL as a separate parameter:
Post.where("poster = ? and (title is not null or name != ?)", #user.id, 'Bob')

Related

Order of operations in ActiveRecord lookup

Approval.where("user1_approval IS NOT NULL AND user2_approval IS NOT NULL AND (user_id = ? OR approved_id = ?)", user.id, user.id)
I want the part in parenthesis to work -- either of those statements. Currently I get an error on the parenthesis when I run this query.
How can I make this query?
Do you mind to use ActiveRecord query like this ?
Approval.where.not(user1_approval:nil).where.not(user2_approval: nil).where("summoner_id = ? OR approved_id = ?", user.id, user.id)
It might reduce the potential problem in writing plain SQL.

Rails activerecord LIKE AND clause error

Here is an activerecord query i'm trying to use in rails
q = "Manchester"
b = "John Smith"
Model.find(:all, :conditions => ["city ? AND name like ?", q, b])
but i get this error in rails console
ActiveRecord::StatementInvalid: SQLite3::SQLException: near "'Manchester'": syntax error: SELECT "model".* FROM "model" WHERE (city 'Manchester' AND name like 'John Smith')
Please help!
You missed LIKE for city.
Model.where('city LIKE ? AND name LIKE ?', "%#{q}%", "%#{b}%");
You can also use this syntax which is a lot more readable than trying to figure out which ? goes with which variable. I mean if you have 1 or 2 it's fine, but once you have more it gets pretty ugly.
Model.where("city LIKE :city AND name LIKE :name", { city: "%#{q}%", name: "%#{b}%" })
The placeholders and hash key can be anything you like as long as they match (don't use :city and then hamster: in the hash key for example).
The nice thing about this is that you can also use one variable for multiple searches:
where("user LIKE :term OR email LIKE :term OR friends LIKE :term", { term: "%#{params[:term]}%"})
Try this:
Model.find(:all, :conditions => ["city = ? AND name like ?", q, b])

checking if params exists in rails

This is what I'd like to do:
I have this piece of code:
customer = Customer.find(:first, :conditions => {:siteId => params[:siteId], :customerCode => params[:id]})
If :customerCode is null, I'd like to use :temporaryCode instead. But I don't know how.
Thanks in advance.
customer = Customer.find_by_siteid_and_customercode params[:siteId], params[:id]
customer ||= Customer.find_by_siteid_and_temporarycode params[:siteId], params[:id]
making use of finders is most safer, cleaner
I'm pretty sure you want to use COALESCE inside the database:
customer = Customer.where(:siteId => params[:siteId])
.where('coalesce(customercode, temporarycode) = ?', params[:id])
.first
The SQL COALESCE function returns the first of its arguments that isn't NULL. For example:
coalesce(column1, column2)
gives you column1 if column1 isn't NULL and column2 if column1 is NULL.
If you're using Rails2 then something like this should work:
Customer.find(:first, :conditions => [
'siteid = ? and coalesce(customercode, temporarycode) = ?',
params[:siteId], params[:id]
])

Does not equal conditional

I want to have a where clause with an equal and does not equal condition:
#user = User.where(:user_id => current_user.id, :author_id != current_user.id).nil? ? (render :something) : (render :somethingelse)
The above does not work:
syntax error, unexpected ')',
expecting tASSOC ...d, :user_id !=
current_user.id).nil? ? (render
:index) : (re...
If I change the second condition from != to => it will work, however.
How do I have both conditions in one where clase? Thank you
Here's how you would use Arel to generate the query "select * from users where user_id = ? and author_id != ?":
users = User.arel_table
User.where(users[:user_id]. eq(current_user.id).and(
users[:author_id].not_eq(current_user.id)))
Using Arel isn't as concise as using Hash conditions for simple conditions, but it's a lot more powerful!
Here's a link to the full list of predications (eq, not_eq, gt, lt, etc.) available with Arel.
I believe, it should be:
#user = User.where(['user_id = ? AND author_id <> ?', current_user.id, current_user.id])
render(#user ? :something : :somethingelse)
Rails 4 has this all figured out
Model.where.not(:colname => nil)
#=> returns all records whose :colname values are not nil
The syntax error is due to you attempting to use != instead of =>. The where method does not support inequality with hashed arguments, so your not equal will need to be written using array arguments.
User.where(:user_id => current_user.id).where(['users.author_id <> ?', current_user.id])
http://guides.rubyonrails.org/active_record_querying.html#hash-conditions
Only equality, range and subset checking are possible with Hash conditions.
You'll need to either drop down to straight SQL or invert and arel query, see Is there a way to invert an ActiveRecord::Relation query?
Not sure if you're aware, the not equal condition typically does not match (author_id) NULL values. You'll have to do an OR author_id IS NULL if you want that.
#users = User.where("user_id = ? AND (author_id != ? OR author_id IS NULL)",
current_user.id, current_user.id)
render(#users.present? ? :something : :somethingelse)
Also note that I'm using #users.present? because where finder returns an ActiveRecord::Relation array.

Not Null in "count" or "find" function in rails

I'm trying to find the not null elements in a database
#genus_counts = Table.count(:all, :conditions=> {:col1 => params[:gm], :col2 => nil}, :without => {:col3 => nil})
It's not recognising "without" function. I am in doubt to apply it as array value.
#genus_counts = Table.count(:all, :conditions=> {:col1 => params[:gm], :col3 != nil :col2 => nil})
It's not recognising "!=" operator.... Kindly suggest me and correct above statement. I am in doubt to apply it as array value.
#genus_counts is a local variable, I can't apply it as array. Kindly tell me the suggestion to bring this output to view.erb.html
--
With Regards
Palani Kannan. K
You should do something like (as answered before)(inside your controller) :
#genus_count = Table.count(:all, :conditions => ['col3 is not null and col2 is null and col1 = ?', params[:gm])
then #genus_count will contain the count you want. Since #genus_count is an instance variable of your controller, you can just refer to it inside your view like this:
The wanted count = <%= #genus_count %>
Hope this helps!
as in
http://guides.rubyonrails.org/active_record_querying.html#conditions
you can use something similar to this form instead:
"orders_count = ? AND locked = ?", params[:orders], false
so you can use
" ... col3 IS NOT null ... "
The hash format of specifying conditions such as :conditions=> {:col1 => params[:gm], :col2 => nil} can only be used to specify conditions that are all = joined with AND.
It's nice to read so use that format when applicable, but when you need an OR, or a comparator other than =, you'll need to use a slightly different format:
:conditions => ["col1 = ? AND col3 != ? AND col2 = ?", params[:gm], nil, nil]
This format takes an array, the first element of which is an sql fragment, and the remaining parameters are sql sanitized (preventing sql injection attack, and converting nil to 'NULL' etc) and inserted into the sql fragment replacing the ? (in order of appearance).

Resources