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).
Related
The Case:
table - movie:
columns:
rating:
title:
Query 1- get all
Movie.all(:order => "title ASC");
Query 2- get with rating="G" || rating="K" ---Not working
ratingsArr=["G","K"]; also can be = [] =>real code params[:ratings] ..
Movie.all(:order => "title ASC", ratingsArr);
How should I build Query 2? ratingsArr may or may not be empty. User set params, according them ratingsArr has the value.
I believe you need to use Movie.where(:rating => ratingsArr).order("title ASC")
Being new, you should read the Rails Guides and perhaps the API documentation for ActiveRecord
Try this:
Movie.where( params[:ratings].present? ? {:rating => params[:ratings]} : {} ).
order("title ASC");
You should be able to use the SQL IN operator by doing: Movie.where(:rating => ratings_array).order("title ASC")
Note that I changed ratingsArr to ratings_array. This is code convention for Ruby. CamelDot is only used for Class names. In variables words are seperated by _
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')
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.
I have a form which is used to filter queries. Some of the form attributes are optional; I'm just wondering how to append them as activerecord conditions if (and only if) they have a set value?
There's a fair few of them, so I'd rather not make a separate query for each pattern of potential values. Any suggestions?
To give a specific example:
people = People.paginate(
:all,
:include => [:people_postcodes, :people_specialties, :people_states],
:conditions => ["people_specialties.people_type_id = %s AND (people_postcodes.postcode_id = %s OR people_states.state_id = %s)" % [self.people_type_id, postcodeid.id, stateid]],
:page => page,
:per_page => 16
)
How would I best go about creating an extra condition (say 'nationality') only if the optional 'nationality' attribute is populated?
First off, your conditions are a little insecure. You're doing basic ruby text substitution, which will let site users inject whatever malicious sql they want. Instead, format it like this:
people = People.paginate(
:all,
:include => [:people_postcodes, :people_specialties, :people_states],
:conditions => ["people_specialties.people_type_id = ? AND (people_postcodes.postcode_id = ? OR people_states.state_id = ?)", self.people_type_id, postcodeid.id, stateid],
:page => page,
:per_page => 16
)
To answer your question, there's no natural way to tack on another condition in Rails 2.x. I would do this:
conditions = ["people_specialties.people_type_id = ? AND (people_postcodes.postcode_id = ? OR people_states.state_id = ?)", self.people_type_id, postcodeid.id, stateid]
if params[:nationality]
conditions.first += " and nationality = ?"
conditions.push params[:nationality]
end
people = People.paginate(
:all,
:include => [:people_postcodes, :people_specialties, :people_states],
:conditions => conditions,
:page => page,
:per_page => 16
)
In the example above, I'm assuming nationality is passed in as a parameter, but adjust as needed. I create the original conditions array, then append the first element (the actual condition string) and add one more element to the end of the array: the nationality value.
I hope this helps!
Hey guys another rails issue,
Currently have a collection that is line items for an invoicing system. I want to increment the count of the line items if I add in an item that already exists. At the moment I'm using an exists? query on the collection but it seems to return regardless of the key.
The foreign key I'm using is item_id, so I try to do invoice_items.exists?(:item_id => item.id)
This wasn't returning, so I changed it to invoice_items.find(:conditions => ["item_id == ?", item.id) and I get a return that I cannot search without invoiceItem ID.
Ideas?
conditions => ["item_id == ?", item.id
should be
conditions => ["item_id = ?", item.id]
So your query look like this
invoice_items.find(:all).conditions => ["item_id = ?", item.id]
you should just need to do either
invoice_items.all(:conditions => ["item_id == ?", item.id])
OR
invoice_items.first(:conditions => ["item_id == ?", item.id])
and you can use the syntax
invoice_items.all(:conditions => {:item_id => item.id})
if you are going to use the model.find command the first parameter needs to be :all, :first, :last or the primary key you are searching for. that is why I generally prefer to use Model.find only if I am searching for an id, otherwise I use Model.first, Model.last, Model.all. That way you know what you are going to get.