Duplicate found queries on Json data - postgress - ruby-on-rails

am having issues in running queries on data which i have been provided,
if i do Camera.first get the results as
#<Camera id: 6, created_at: "2013-12-12 17:30:32", updated_at: "2015-11-19 10:19:33", exid: "dublin-rememberance-floor2", owner_id: 4, is_public: true, config: {"snapshots"=>{"jpg"=>"/onvif/snapshot"}, "external_http_port"=>8105, "external_host"=>"89.101.225.158", "auth"=>{"basic"=>{"username"=>"admin", "password"=>"mehcam"}}}, name: "My Camera", last_polled_at: "2015-11-27 15:01:51", is_online: false, timezone: nil, last_online_at: "2014-05-01 09:45:39", location: "0101000020E6100000875341A08E0A19C0D6BB896BC6AC4A40", mac_address: nil, model_id: 6, discoverable: false, preview: nil, thumbnail_url: nil>
I am totally unaware about how to get the query run CONFIG object.
example: I want to select all the Cameras list which have same
"external_http_port"=>8105, "external_host"=>"89.101.225.158"
but they are in Config Object.

You can write query like following for json data fetch:
Camere.where("config->> 'external_http_port' = ? and config->> 'external_host' = ?", 8105, '9.101.225.158')

Related

How to change the object view in paper_trail

I have used paper_trail gem for auditing in the application i am developing. I am able to manage most of its features and i was able to display the data in versions table to the user. In doing so the data in object attribute of the versions table is some what unreadable. How can i make it be readable?
Here is my sample output of the object attribute:
version.object retrieves in the following format in a single cell:
--- budget_year: '2014' name: bbb reference_number: j789789 requesting_unit: '798789' quarter: II source_of_fund: Government budget_type: Recurrent procurement_method: Open Bidding procurement_level: National estimated_cost: 4455.0 currency: '4545' purchase_request_id: start_at: 2014-07-30 end_at: 2014-07-31 created_at: 2014-07-24 08:29:38.000000000 Z updated_at: 2014-07-24 08:29:38.000000000 Z id: 1
You could use reify method to see your data like,
> i=Invoice.last.versions.last
=> <PaperTrail::Version id: 158, item_type: "Invoice", item_id: 115, event: "update", whodunnit: "3", object: "---\nid: 115\ncreated_at: 2015-02-05 06:43:17.278448...">
:038 > i.object
=> "---\nid: 115\ncreated_at: 2015-02-05 06:43:17.278448000 Z\nupdated_at: 2015-02-05 06:43:17.278448000 Z\nentity_type: Site\nentity_id: 928\ninvoice_id: WS/14\nuser_id: \nperson_id: \nstatus: 0\nperson_email:\nentity_value:\naddress: ''\nprice: '666'\ndetails: '{\"domain\"=>\"\", \"package\"=>\"23\", \"site_id\"=>\"928\", \"user_id\"=>\"394\", \"years\"=>\"1\"}'\norder_id: '464'\nnorder_type: \nyear: 1\npayment_type: cash\naccount_type: \ncheque_name: ''\ncomment: \ntax: \ncomments: 'Customer made payment by cash with receipt Nos: 041 & 042.'\ncheque_number: \nchequenumber: ''\npayment_level: \ninvoice_type: \n"
> i.reify
=> <Invoice id: 115, created_at: "2015-02-05 06:43:17", updated_at: "2015-02-05 06:43:17", entity_type: "Site", entity_id: 928, invoice_id: "WS/14-15/D-2119", user_id: nil, person_id: nil, status: 0, address: "Near So...", price: "4999", details: "{\"domain\"=>\"\", \"package\"=>\"23\", \"site_id\"=>\"928\", ...", order_id: "464", order_type: nil, year: 1, payment_type: "cash", account_type: nil, cheque_name: "", comment: nil, tax: nil,, cheque_number: nil, chequenumber: "", payment_level: nil, invoice_type: nil>
or
> PaperTrail.serializer.load(i.object)
=> {"id"=>115, "created_at"=>2015-02-05 06:43:17 UTC, "updated_at"=>2015-02-05 06:43:17 UTC, "entity_type"=>"Site", "entity_id"=>928, "invoice_id"=>"W", "user_id"=>nil, "person_id"=>nil, "status"=>0, "person_email"=>"rium#gmail.com", "entity_value"=>"u.com", "address"=>"li ", "price"=>"4999", "details"=>"{}", "orr_id"=>"655", "processed_by"=>"", "order_type"=>nil, "year"=>1, "payment_type"=>"cash", "account_type"=>nil, "cheque_name"=>"", "comment"=>nil, "tax"=>nil, "comments"=>"Customer made payment by cash with receipt Nos: 041 & 042.", "cheque_number"=>nil, "chequenumber"=>"", "payment_level"=>nil, "invoice_type"=>nil}
second way will give the form of hash.

Rails 4 to_json produces unexpected Exception nil is not a symbol

I am in the process of upgrading a Rails 3 application to Rails 4. In Rails 3 the json serialization of a hash containing an array of ActiveRecord objects was working correctly; now in Rails 4 it is having unpredictable results.
Here is an example object that fails with TypeError Exception: nil is not a symbol on Rails 4
{1230 =>
[
#<QuestionAnswerResponse response_id: 127, response_set_id: 6, response_group: nil, question_data_export_identifier: "is_co_pi_involved", answer: "No", question_id: 1230, answer_id: 2077, response: "">,
#<QuestionAnswerResponse response_id: 131, response_set_id: 6, response_group: nil, question_data_export_identifier: "is_co_pi_involved", answer: "No", question_id: 1230, answer_id: 2077, response: "">
]
}
Now if I take another similar object; hash containing an array of ActiveRecord objects and run to_json it works on this one...
{1234 =>
[
#<Response id: 1, response_set_id: 2, question_id: 4, answer_id: 2, datetime_value: nil, integer_value: nil, float_value: nil, unit: nil, text_value: nil, string_value: nil, response_other: nil, response_group: nil, created_at: "2014-05-30 21:17:23", updated_at: "2014-05-30 21:17:23", survey_section_id: 1, api_id: "f44b22ba-a93b-477f-8a7f-c5b4566338f0", attach_file_name: nil, attach_content_type: nil, attach_file_size: nil, attach_updated_at: nil>,
#<Response id: 2, response_set_id: 2, question_id: 10, answer_id: 10, datetime_value: nil, integer_value: nil, float_value: nil, unit: nil, text_value: "test", string_value: nil, response_other: nil, response_group: nil, created_at: "2014-05-30 21:17:23", updated_at: "2014-05-30 21:17:23", survey_section_id: 1, api_id: "e7fa8aa2-6e47-4f88-8802-949fdc902a2e", attach_file_name: nil, attach_content_type: nil, attach_file_size: nil, attach_updated_at: nil>
]
}
The view backing my QuestionAnswerResponse model does not have an id column and I was not setting a primary key in the model. In the capacity that I use this model I do not need a primary key; this is a read only view used to more easily access some complex key/value pairings directly instead of through more complex logic.
In Rails 3 this worked fine; in Rails 4 when you access a model without a primary key you end up with an attribute that looks like this in your hash nil => nil
The problem is actually up at the ActiveRecord level, but wasn't actually causing a problem until I attempt to do json serialization; at which point in time an attempt is made to call nil.to_sym which raises the exception.
This seems like a bug in ActiveRecord to me; but for now I have worked around it by manually setting a primary key on my model.

Rails where clause not equal to nil

Hey folks trying to do a simple query where I find all records where a particular attribute is nil. In this case...
irb(main):009:0> Registration.where(:registration_cancellation_token != nil)
Registration Load (0.2ms) SELECT `registrations`.* FROM `registrations` WHERE (1)
=> [#<Registration id: 1, orientation_id: 13, first_name: "mark", last_name: "Busta", email: "marklocklear#gmail.com", student_id: "3232333", phone: "3884448333", registration_cancellation_token: nil, registration_cancelled_at: nil, checked_in: false, created_at: "2014-02-20 13:46:31", updated_at: "2014-02-20 13:46:31">]
...but the query is returning all registrations. Any help appreciated...
Registration.where("registration_cancellation_token IS NOT NULL")
Registration.where.not(registration_cancellation_token: nil)
This works for Rails 4

Nil return where it should be exist a value

I'm playing on rails console and did the following steps:
agendamento = Agendamento.last
And got a record that looks like this
#<Agendamento id: 4, sala_id: 2, name: "Delta C", start_at: "2013-10-11 02:00:00", end_at: "2013-10-10 04:00:00", bookingDate: "2013-10-10",
bookingTime: "2000-01-01 23:00:00", bookingDuration: 2, approved: true, usuario_id: nil, created_at: "2013-10-05 02:24:00", updated_at: "2013-
10-05 02:24:00">
when I do agendamento.name I receive:
Delta C
and it works in all values, but not on sala_id, agendamento.sala_id returns
nil
This attribute is acessible in the model, why it is returning nil ?
Environment: Ruby 2 and Rails 4
If sala_id is a foreign key reference, have you tried invoking sala instead? That should give you the related object.

Finding elements in array of hashes

I'm trying to build a model of products which has many components. Some components are optional and depend on the choice the user is making to enable them or not.
I have two models, one is configuration and the other is elements (of that configuration).
At the beginning I bring all the elements of the array, and then create another array of those which will be shown by default.
But when I write the following code it gives me an error despite both objects being arrays of hashes.
So I bring my first array of all elements:
irb(main):252:0* #all = Configuration.find(1).elements
=> [#<Element id: 1, name: "elem1", quantity: 1, position: 1, subposition: nil, created_at: nil, updated_at: nil, configuration_id: 1>, #<Element id: 2, name: "elem2", quantity: 2, position: 2, subposition: 1, created_at: nil, updated_at: nil, configuration_id: 1>, #<Element id: 3, name: "elem3", quantity: 3, position: 2, subposition: 2, created_at: nil, updated_at: nil, configuration_id: 1>, #<Element id: 4, name: "elem4", quantity: 4, position: 3, subposition: nil, created_at: nil, updated_at: nil, configuration_id: 1>]
Then I filter to be only those that have a subposition nil or 1
irb(main):253:0> #default = #all.where(:subposition=>nil).concat(#all.where(:subposition=>1))
=> [#<Element id: 1, name: "elem1", quantity: 1, position: 1, subposition: nil, created_at: nil, updated_at: nil, configuration_id: 1>, #<Element id: 4, name: "elem4", quantity: 4, position: 3, subposition: nil, created_at: nil, updated_at: nil, configuration_id: 1>, #<Element id: 2, name: "elem2", quantity: 2, position: 2, subposition: 1, created_at: nil, updated_at: nil, configuration_id: 1>]
So far so good, as you can see, Elem3 is not being shown in #default as it doesn't meet the requiements.
The problem comes when I try to play with the arrays as I need to perform certain operations.
irb(main):257:0> #all.where(:position =>1)
=> [#<Element id: 1, name: "elem1", quantity: 1, position: 1, subposition: nil, created_at: nil, updated_at: nil, configuration_id: 1>]
But the same operation in #default will fail,
irb(main):258:0> #default.where(:position =>1)
NoMethodError: undefined method `where' for #<Array:0x2641660>
Now, they're both arrays of hashes and look the same, why is the same method failing in the second case?
Thanks a lot for your help!
Throughout your code, #all is an ActiveRecord::Relation, not an array. This lets you perform the standard .where call (among others). When you assigned to #default, you used .concat which evaluated the query and assigned an actual array to #default.
You might try a different approach in your second code block. Maybe something like this:
#default = #all.where("subposition is null or subposition = ?", 1)
Well, your problem is that concat transforms a collection into an array.
I'd replace:
irb(main):253:0> #default = #all.where(:subposition=>nil).concat(#all.where(:subposition=>1))
by:
#default = #all.where("subposition = '1' OR subposition = nil") #I'm unsure of the nil in the statement, I nerver remember, try NULL if it fails
This way, you make only one db query and you keep an ActiveRecord collection.
Thus, you'll be able to chain other where conditions on it.

Resources