I'm trying to fetch the record which the fields are not null.
for example I'm having a jsonb column in my table like this
job_metadata jsonb DEFAULT '{}'::jsonb NOT NULL
i want to fetch the record of job_metadata hash of key enqued_at, which are not null.
i tried something like
TimeBox.where.not('job_metadata #> ?', '{"enqueued_at": nil}')
but i got the error like
PG::InvalidTextRepresentation: ERROR: invalid input syntax for type json
LINE 1: ... 38, 39, 40, 51, 52, 53, 32) AND (job_metadata #> '{"enqueued_at...
how to fix the error, or how to fetch the records where the job_metadata -> enqueued_at should not be nil?
This should work.
TimeBox.where("(job_metadata->'enqueued_at') is not null")
Related
I have a json column (is an array of objects) in my db containing the many categories related to a product like this:
[
{
"id": 1,
"name": "Category X"
},
{
"id": 2,
"name": "Category Y"
},
...
]
I need to translate into active record query the following PostgreSQL query:
SELECT * FROM products p, json_array_elements(p.category) as data
WHERE data ->>'name' = 'Sport';
Some of queries that I tried:
sports = Product.where("category ->>'name' = ?", "Sport")
Which returns an empty array (It is wrong since I have records with Sport category in my db)
sports = Product.where("category #> ?", [{name: "Sport"}])
Which raises: TypeError: can't quote Hash
sports = Product.where("category #> ?","{name: 'Sport'}")
Which raises: ERROR: operator does not exist: json #> unknown
and the Hint: No operator matches the given name and argument type(s). You might need to add explicit type casts.
So I tried:
sports = Product.where("category #> ?", "[{'name': 'Sport'}]")
and
sports = Product.where("category #> ?", "[{'name': 'Sport'}]".to_json)
and some other queries all without success.
These links:
PostgreSQL functions-json
active record querying
didn't help much.
The reason why you're getting a PG::UndefinedFunction: exception ("operator does not exist: json #> unknown") is because the #> operator is meant to be used in jsonb data type columns, and your products.category column isn't.
For that you can; or to update the data type of the category column, or to explicitly cast the column at the moment of performing the query:
Product.where('category::jsonb #> ?', [{ name: 'Sport' }].to_json)
This:
Product.where("category #> ?", "[{'name': 'Sport'}]")
isn't going to work, since it's not valid syntax.
Trying to perform an Arel query. In my params I have
{"node"=>"firstSeenAt", "rule"=>"hasAnyValue", "value"=>""} where first_seen_at is a column in my visitors table
def table
visitors.arel_table
end
def rule_has_any_value
visitors.where(table["#{column}"].not_in_any(["", nil, 0]))
end
keep getting this in my Rails console
ActiveRecord::StatementInvalid (PG::UndefinedFunction: ERROR: operator does not exist: timestamp without time zone = integer
LINE 1: ... IN (NULL) OR "visitors"."first_seen_at" NOT IN (0)) OR...
^
HINT: No operator matches the given name and argument types. You might need to add explicit type casts.
):
Any pointers on what's wrong here? Thank you.
What I wrong with me or this query?
I have a Shop model with an opening days column, which is an array of integers (something you can do with Postgres):
days= [1,1,1,1,0,0,0]
When I query:
shops = Shop.where('days[0] = 1')
I get an empty ActiveRecord Relation.
=> #<ActiveRecord::Relation []>
When I take a shop with this kind of array…
shop = Shop.first
=> #<Shop id: 215, days: [1, 1, 1, 1, 0, 0, 0],…
If I do
shop.days[0]
I get
=> 1
I really don't get it.
By default PostgreSQL uses a one-based numbering convention for arrays, that is, an array of n elements starts with array[1] and ends with array[n].
— Source
It's just your example. Your index is out of bounds, so it doesn't match any records, days[0] is NULL. Everywhere. Fire up rails db and figure:
SELECT * FROM shops WHERE days[0] IS NULL;
But what's with that "by default"? Is it possible to define array bounds on schema level so this never becomes an issue?
Well... it's Rails' fault, I'm afraid. If it's even considered an "issue" at all. In order for an array to be zero-indexed it should be saved as such in SQL. I tried that in SQL, it works:
INSERT INTO shops
(days, created_at, updated_at)
values('[0:2]={1, 1, 0}', current_timestamp, current_timestamp);
Unfortunately, Rails loses bounds for some reason:
Shop.create(days: '[0:3]={6, 7, 8, 9}')
> INSERT ... [["days", "{6,7,8,9}"], ...]
I have model integration with associated model integration_profiles with a json column called data
Trying to query and group by the date with truncation.
i.integration_profiles.select("date_trunc('hour', timestamp data ->> 'created_at' )").group("data ->> 'created_at'")
Get this error:
PG::SyntaxError: ERROR: syntax error at or near "data"
LINE 1: SELECT date_trunc('hour', timestamp data ->> 'created_at' ) ...
TableName : NameYear
This is my Table
ID name min_max_year
1 xyz [1970,1971...2014]
2 abc [1980,1981...2014]
2 pqr [2000,2001...2014]
Now I want to find records that MinMaxYear include 1980.
Than How Can I do?
I try this way : NameYear.where("min_max_year IN (?)", 1980)
but getting this error :
ActiveRecord::StatementInvalid: PG::Error: ERROR: operator does not exist: text = integer
LINE 1: ...ROM "name_year" WHERE (min_max_year IN (1980))
You need to use the ANY clause on the array column:
SELECT * FROM NameYear
WHERE 1980 = ANY(min_max_year);
The ActiveRecord statement would be:
NameYear.where("? = ANY(min_max_year)", 1980)
This selects any record whose min_max_year column contains a value of 1980.