How to read json in Rails Controller? - ruby-on-rails

So, I'm doing like that at my controller action:
json_document = JSON(params) (json gem)
If I print json_document it gives me a Json like that:
{"createdAt":"Mar 6, 2012 6:12:54 PM","id":177139718620856322,"text":"#rgjunio where?","source":"web","isTruncated":false,"inReplyToStatusId":177139644012572673, ...
But when I try to access it:
tweet = Complaint.find_by_twitter_status json_document["inReplyToStatusId"]
i get the following error:
can't convert ActiveSupport::HashWithIndifferentAccess into String
So i tried another way using symbols:
tweet = Complaint.find_by_twitter_status json_document[:inReplyToStatusId]
but it gives me the error:
TypeError (can't convert Symbol into Integer)
Any idea?
Update:
If I use params[:inReplyToStatusId] isntead I got the following:
ActiveRecord::StatementInvalid (PG::Error: ERROR: operator does not exist: character varying = bigint
HINT: No operator matches the given name and argument type(s). You might need to add explicit type casts.
SELECT "complaints".* FROM "complaints" WHERE "complaints"."twitter_status" = 177144980450721794 LIMIT 1):

Try:
params[:inReplyToStatusId].to_s

Related

unknown LINE 1: select "id" from"notifications" where"data"->>'id' = $1 You might need to add explicit type casts(SQL: select"id"from"notifications"

i make project with laravel and i upload it on the heroku i used notifications so data column in notification table stored like {"id":36,"total":"300","tableNum":"6"} these data for order
i used this code to make notification unread
public function show($id) //$id refers to order id in this example id = 36
{
$getId = DB::table('notifications')->where("data->id", $id)->pluck('id');
DB::table('notifications')->where('id', $getId)->update(['read_at' => now()]);
return redirect()->route('current');
}
this code runs without any errors, but in heroku make an error "cast" what can i do ?
SQLSTATE[42883]: Undefined function: 7 ERROR: operator does not exist: text ->> unknown
LINE 1: select "id" from "notifications" where "data"->>'id' = $1
^
HINT: No operator matches the given name and argument types. You might need to add explicit type casts. (SQL: select "id" from "notifications" where "data"->>'id' = 1)
You have a syntax error in your current example.
->where("data->id", $id)
It should either be "id" or $data->id, but it's hard to assume based from the code you just posted. However, your answer could be simplified by just using this. Don't need to pluck id and use it again for another query
public function show($id) //$id refers to order id in this example id = 36
{
DB::table('notifications')->where('id', $id)->update(['read_at' => now()]);
return redirect()->route('current');
}

Concatenation of values

I am trying to concatenate the ":" sign with value that is inside a variable but when trying to concatenate it shows me the following error: bad URI(is not URI?): :208
This is the code I am trying to concatenate in the ApplicationController:
def set_database
if usuario_signed_in?
empresa = ':'+(current_usuario.empresa_id)
ActiveRecord::Base.establish_connection(empresa)
end
With the previous code does not work, but replacing the variable as follows does not show the error:
if usuario_signed_in?
empresa = :'208'
ActiveRecord::Base.establish_connection(empresa)
end
yeah those are 2 different things
empresa = ':'+(current_usuario.empresa_id)
would probably resolve to a string or an error while
empresa = :'208'
is a symbol.
I believe you can solve this issue by just converting your empresa to a symbol, either by calling
current_usuario.empresa_id.to_sym
OR
current_usuario.empresa_id.to_s.to_sym
The error is telling you the URL is not valid, you need to encode it and parse it. See How to fix bad URI is not URI

Where not null for reference column showing error - rails

I want to query a table where multiple referenced column in not null.
I tried like this:
JobTypePresetting.where('comment_text == ?', nil)
JobTypePresetting.where('comment_text_id == ? OR part_listing_id == ?', nil, nil)
Even first is not working showing error like
ActiveRecord::StatementInvalid: PG::UndefinedFunction: ERROR: operator does not exist: integer == unknown
LINE 1: ...resettings"."template_id" = $2 AND (comment_text_id == NULL)
^
HINT: No operator matches the given name and argument type(s). You might need to add explicit type casts.
How do i query this, currently i'm using like
JobTypePresetting.where('comment_text_id is not null or part_listing_id is not null')
You need to use single(=) oprator.
JobTypePresetting.where('comment_text = ?', nil)
Hope this may work for you.
Try to use Arel, much easier to construct complex sql queries. They have been part of rails from 3 release. https://github.com/rails/arel
jtp = JobTypePresetting.arel_table
JobTypePresetting.where(jtp[:comment_text_id].not_eq(nil).or(jtp[: part_listing_id].not_eq(nil)))
Hope it helps

Rails/Postgres nested JSON query

I have a JSON column in my events table called payload. I can create an event like this:
Event.create!(application_id: 1, stage: 'INITIATION', payload: { key: 'OUTCOME', value: {school_id: 2, prefered_language: 'GBP'}})
Simple queries like
Event.where("payload->>'key' = ?", "OUTCOME")
Will work fine, but how can I then add extra filters with the JSON that's nested in the value portion
Event.where("payload->>'key' = ? AND payload ->>'value'->>'school' = ?", "OUTCOME", 2)
^^^^^^^^^^^^^^^^^^^^
I tried that but i got:
PG::UndefinedFunction: ERROR: operator does not exist: text ->> unknown
LINE 1: ...ad ->>'key' = 'INPUTPARAMS' AND payload ->>'value'->>'school... ^
HINT: No operator matches the given name and argument type(s). You might need to add explicit type casts.
How do I get into the school attribute within value?
I have taken the idea from this documentation on ActiveRecord and JSON
After much searching, I came across this article.
The #>> operator allows you to dig inside the JSON. My query could be fixed like this.
Event.where("payload->>'key'= ? AND payload#>>'{value, school_id}' = ?", 'OUTCOME', shcool_id)
You could theoretically go down further by adding each layer to the predicate block {value, school, next_level, and_so_on}

Generic Parsing Error

In a 4D application, I have the following lines of code:
Begin SQL
UPDATE Keys
SET Desc = :$desc,
KeyStamp = :$key_stamp
WHERE KeyTitle = :$key_title
End SQL
When trying to run the code, the following error is displayed:
Generic parsing error. Parsing failed in or around the following
substring interval - ( 16, 23 ) - ... SET Desc = ...
Does anyone see the problem with the code? Keys is not a keyword or anything, is it?
Seems like someone forgot that Desc is a keyword for "descending." The solution is to rename the column and update all references to that column. Otherwise, the column cannot be referenced in SQL.

Resources