Where not null for reference column showing error - rails - ruby-on-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

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');
}

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}

SQLite select statement assertion failure in iOS

I get an assertion failiure on this statement;
SELECT keyphrase_id, keyphrase, url, googlename FROM keyphrases left join domains on keyphrases.domain_id = domains.domain_id where domain_id = ? and ifnull(keytime,'') != ? order by keyphrase desc;
I ran it through a SQL query checker and it highlighted the "!=" bit citing it wasn't correct syntax. This doesn't make sense to me since I was using this statement previously;
SELECT keyphrase_id, keyphrase, url, googlename FROM keyphrases left join domains on keyphrases.domain_id = domains.domain_id where ifnull(keytime,'') != ? order by keyphrase desc;
This is how I bind the where values;
sqlite3_bind_int(selStmt, 1, domain_ID);
sqlite3_bind_text(selStmt, 2, [dateString UTF8String] , -1, SQLITE_TRANSIENT);
I can't work this out at all and it's definitely nothing to do with the database being open or the statement being nil when executing etc. since the only component of the method I'm changing is the SQL statement.
Can anyone suggest any possible reasons for this?
If you get a return code from any sqlite3 function call that suggests an error, do another call to sqlite3_errmsg and look at the error message, e.g.
NSLog(#"%s err: %s", __FUNCTION__, sqlite3_errmsg(database));
This will tell you what's wrong.
Personally, I would have thought that the reference to domain_id in the where clause was ambiguous, but the sqlite3_errmsg will tell you precisely what's going on.

Squeel evaluating a string as a keypath for joins

Here's what I'd really like to do:
Outage.joins{eval "unit.plant"}
I'm going to have a string that represents a squeel keypath. I'd like to send this string into a join statement.
But here's what I get as an error:
#<Class:0x639e328>: unknown class: Squeel::Nodes::Function
I've tried:
Outage.joins{"unit.plant"}
But that does not work... what am I missing?
I don't see any documentation on this on the github page: https://github.com/ernie/squeel/
Thank you for any help!
Update:
I've found a really confusing way to pull this off:
("unit.plant".split ".").map{ |x| x.to_sym }.reverse.inject{ |acc, x| { x => acc } }
This will output:
{:unit=>:plant}
This can be passed into the joins squeel function. I'm sure there has to be a better way than to construct nested symbols :(
How about
Outage.joins{Squeel::Nodes::KeyPath.new("unit.plant".split("."))}
Source: KeyPath Docs
Alternative solution, it can be chained with outer/inner:
strs = "unit.plant"
Outage.joins{strs.split(".").inject((strs.present? ? self : nil), :__send__)}
# chain with inner
# Outage.joins{strs.split(".").inject((strs.present? ? self : nil), :__send__).inner}

How to read json in Rails Controller?

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

Resources