Here is my query
query = "(description = ? AND address1 = ?) AND (city = (?) OR old_city = (?) OR cb_city = (?))"
Input data :
office_data = {"description"=>"Europe HQ", "city"=>"Dublin", "street_1"=>nil}
But When I queries as
office = company.offices.where(query, office_data["description"], office_data["street_1"], office_data["city"], office_data["city"], office_data["city"]).first
Equivalent SQL:
SELECT "offices".* FROM "offices" WHERE "offices"."company_id" = 6 AND ((description = 'Europe HQ' AND address1 = NULL) AND (city = ('Dublin') OR old_city = ('Dublin') OR cb_city = ('Dublin'))) LIMIT 1
Getting result as
nil
Though I am records in company.offices
As
[#<Office id: 393, company_id: 6, description: "Europe HQ", address1: nil, address2: nil, zip_code: nil, city: nil, state_code: nil, country_code: nil, latitude: nil, longitude: nil, created_at: "2014-08-19 15:13:58", updated_at: "2014-08-19 15:13:58", cb_city: "Dublin", cb_state_code: nil, cb_country_code: "IRL", old_city: nil, region_code: nil, is_hq: nil, cb_region: "Dublin", cb_updated: "2014-04-20 10:53:24", city_uuid: "97c70aa17568ca5375122f181f0484a7", city_path: "location/dublin/97c70aa17568ca5375122f181f0484a7">, #<Office id: 389, company_id: 6, description: "Europe HQ", address1: nil, address2: nil, zip_code: nil, city: nil, state_code: nil, country_code: nil, latitude: nil, longitude: nil, created_at: "2014-08-19 15:02:44", updated_at: "2014-08-19 15:02:44", cb_city: "Dublin", cb_state_code: nil, cb_country_code: "IRL", old_city: nil, region_code: nil, is_hq: nil, cb_region: "Dublin", cb_updated: "2014-04-20 10:53:24", city_uuid: "97c70aa17568ca5375122f181f0484a7", city_path: "location/dublin/97c70aa17568ca5375122f181f0484a7">]
Don't What's wrong with query? Anyone knows what's wrong?
As pointed out by #Mischa and #Victor, the problem is indeed "NULL =". To solve the problem change the "query" parameter as below:
query = "(description = ? AND (address1 = ? OR address1 is NULL)) AND (city = (?) OR old_city = (?) OR cb_city = (?))"
No change is required to "office_data" parameter or your query.
Similarly, you may also need to make a change for city and other parameters too. As these can also have a NULL value
The problem is comparing address with NULL using the = sign - every operation besides IS against NULL is false. Because of that you end up with (true AND false) and (...), resulting in false.
Note that the second query you added in the comments contains no address = NULL - that's why it works in that case.
Related
Why is it when i display the jason for #portfolio_items I get the data only for Portfolio and not the technologies but when i do #portfolio_items.technologies I only get the records for the technologies
I want a jason object that contains both
#portfolio_items = Portfolio.includes(:technologies).find(27)
puts json: #portfolio_items
returns
Portfolio id: 27,
title: "Portfolio title: 0",
subtitle: "Angular",
body: "Lorem ipsum dolor sit amet, consectetur adipiscing...",
main_image: "https://via.placeholder.com/600x400",
thumb_image: "https://via.placeholder.com/350x200",
created_at:"2018-12-28 23:18:35",
updated_at: "2018-12-28 23:18:35"
and
puts json: #portfolio_items.technologies
returns
[#<Technology id: 7, name: "Technology 0", portfolio_id: 27, created_at:
"2018-12-28 23:18:35", updated_at: "2018-12-28 23:18:35">,
<Technology id: 8, name: "Technology 1", portfolio_id: 27, created_at
:"2018-12-28 23:18:35", updated_at: "2018-12-28 23:18:35">,
<Technology id: 9, name: "Technology 2", portfolio_id: 27, created_at:
"2018-
12-28 23:18:35", updated_at: "2018-12-28 23:18:35">]
So basically why is #portfolio_items not have the value thats in portfolio_items.technologies
It is because .technologies is a method being called on the #portfolio_items object which will return technologies related to it, but it does not mix them together which I think it what you are asking about. To display this as a nested JSON object you would want something like this.
puts #portfolio_items.as_json(include:{technologies:{}})
This might help if you are curious about it: https://apidock.com/rails/ActiveModel/Serializers/JSON/as_json
In part of my code I need to grab users's id but pluck doesn't grab them. Only map(&:id) can do it. I was wondering why.
I've wrote a quick and dirty block of code to find what's happen
def remove_users user_ids
p users_to_remove.class
users_to_remove = self.users.where(id: user_ids)
if users_to_remove.present?
self.users -= users_to_remove
self.save
p users_to_remove.class
p users_to_remove
Rails::logger.info "\n#{users_to_remove}\n"
users_to_remove_map = users_to_remove.map(&:id)
p users_to_remove_map
Rails::logger.info "\nmap id: #{users_to_remove_map}\n"
users_to_remove_pluck = users_to_remove.pluck(:id)
p users_to_remove_pluck
Rails::logger.info "\npluck id: #{users_to_remove_pluck}\n"
#...
end
self.user_ids
end
Who return in my test.log
#<User::ActiveRecord_AssociationRelation:0x007fb0f9c64da8>
map id: [144004]
(0.3ms) SELECT "users"."id" FROM "users" INNER JOIN "groups_users" ON "users"."id" = "groups_users"."user_id" WHERE "groups_users"."group_id" = $1 AND "users"."id" IN (144004, 144005) [["group_id", 235819]]
pluck id: []
And in my test
User::ActiveRecord_AssociationRelation
User::ActiveRecord_AssociationRelation
#<ActiveRecord::AssociationRelation [#<User id: 144004, created_at: "2015-08-06 08:55:11", updated_at: "2015-08-06 08:55:11", email: "user_2#test.com", token: "rpf5fqf5bs1ofme6aq66fwtcz", reset_password_token: nil, sign_in_count: 0, current_sign_in_at: nil, last_sign_in_at: nil, current_sign_in_ip: nil, last_sign_in_ip: nil, disabled: false, first_name: "John_2", last_name: "Rivers_4", is_owner: false, organisation_id: 235826, encrypted_password: "$2a$04$8ev1j...f6ICL.ezS....", reset_password_sent_at: nil, default_language: nil, uid: nil, api_key: "rmhh...noyn">]>
[144004]
[]
The strange thing is. I have user with id. map can get them. pluck not.
I don't understand sql log also. How can I get map id result without any select in sql log? Caching ?
pluck doesnt work on an array, it works on an ActiveRecord::Relation, it's goal is to avoid to make a full query to only get the ids.
Once you've retrieved all columns from db, you can just map what you need.
You create the array when you do self.users -= users_to_remove, or maybe even when you do .present?, since you should use .exists?
This line:
users_to_remove = self.users.where(id: user_ids)
Doesn't fire off SQL query immediately. It sends the request whenever you need some details of these users. And it caches the result in SQL cache (so when the same request goes to DB again, it intercepted by Rails and never reaches the database).
So when you call:
users_to_remove.map(&:id)
It uses that cached result. But when you use
users_to_remove.pluck(:id)
It re-fetches the result, because the actual SQL query differs. With #map it is SELECT * FROM ..., and with #pluck it's SELECT id FROM.... And when query reaches the database, IDs doesn't belong to 'self' any longer (you deleted them right before that), so they aren't returned.
I am running this query
Device.joins(:reviews).group(:brand).average(:average_rating)
...and get this output
{#<Brand id: 1, name: "Phonak", created_at: "2013-08-26 22:25:07", updated_at: "2013-08-26 22:25:07">=>#<BigDecimal:6b4dc90,'0.788E2',18(45)>, #<Brand id: 2, name: "Oticon", created_at: "2013-08-29 21:03:06", updated_at: "2013-08-29 21:03:06">=>#<BigDecimal:6b4e320,'0.8070000712 076823E2',27(45)>, #<Brand id: 5, name: "Siemens", created_at: "2013-09-07 21:34:18", updated_at: "2013-09-07 21:34:18">=>#<BigDecimal:6b4eb68,'0.8111111111 111111E2',27(45)>, #<Brand id: 7, name: "Resound", created_at: "2013-09-13 16:10:34", updated_at: "2013-09-13 16:10:34">=>#<BigDecimal:6b4f090,'0.7342857142 857143E2',27(45)>}
However, I would like to have the results grouped by brand name not the actual Brand objects. Is this possible.
I tried:
Device.joins(:reviews).group('brand.name').average(:average_rating)
....but this is not working
I would try with
Device.joins(:reviews).includes(:brand).group("brands.name").average(:average_rating)
Hi am trying out a query and is giving me strange results. I am trying to get a list of object where a field doesn't exist with a where clause added to it.
Step one the where clause:
ContentMirror.where(source: 'some_source').count
This query returns 9984 records.
some_source have a field call vid_emded_obj which I know some are nil For example:
ContentMirror.find('50fff286781200986e000ae3')
=> #<ContentMirror _id: 50fff286781200986e000ae3, _type: nil, created_at: 2012-12-15 13:12:22 UTC, updated_at: 2013-01-29 12:10:23 UTC, deleted_at: nil, title: "Introduction to Polynomials", vid_emded_obj: nil, media_type: "video", source: "some_source", thumbnail_url: nil, md5: "459173975a7fb145b3ca8b99e1c2ae78">
So I was expecting that at lest that count of 1 will return if I do this:
ContentMirror.where(source: 'some_source').exists(vid_emded_obj: false).count
=> 0
Cannot work out why...
I belkieve that exists checks if the property is there at all, and will return true if the value of that property is empty.
I will just go hunt for the doc to confirm :)
EDIT:
So, the doc does not mention any exists(...).
Only an exists? method that can be applied on a criteria.
I think you should do (pseudo code, I haven't tried it)
ContentMirror.count(vid_embed_obj:nil, source: 'some_source')
or
ContentMirror.where(vid_embed_obj:nil, source: 'some_source').count
or again
ContentMirror.excludes(vid_embed_obj:nil).where(source: 'some_source').count
Heres is the output:
(rdb:5) Morphology::MatrixView
Morphology::MatrixView(Table doesn\'t exist)
(rdb:5) Morphology::MatrixView.table_name
"morphology_matrix_view"
(rdb:4) Morphology::MatrixView.all.first
#<Morphology::MatrixView name: "anex", description: nil, copied_from: nil, created_by: "", created_at: "2012-12-14 18:40:51", updated_by: "", updated_at: "2012-12-14 18:40:51", id: 7, matrix_id: 7, copied_from_id: nil, project_id: 81>
(rdb:4) Morphology::MatrixView.all.first.name
"anex"
(rdb:4) Morphology::MatrixView.where(:name => 'anex')
INTERNAL ERROR!!! No attribute named `name` exists for table `morphology_matrix_view`
(rdb:12) Morphology::MatrixView.where("name = ?", "anex")
[#<Morphology::MatrixView name: "anex", description: nil, copied_from: nil, created_by: "", created_at: "2012-12-14 18:40:51", updated_by: "", updated_at: "2012-12-14 18:40:51", id: 7, matrix_id: 7, copied_from_id: nil, project_id: 81>]
I have a model that represents a database view (postgres).
Basically model.where(:attribute => "string") throws an error,
but model.where("attribute = ?", "string") does not.
Not sure how to proceed here, any suggestions (using activerecord 3.0)?