i am trying to write a scope for the model Event
i want to display all events that have expired and have been closed
schema
create_table "events", force: :cascade do |t|
t.string "title"
t.text "description"
t.date "date"
t.boolean "close"
end
event.rb
scope :expired_or_closed_events, -> {where(['close = ? OR close IS ?', true] || ['date < ?', Date.current])}
i tried the above scope but i get the below error
2.3.0 :014 > events.expired_or_closed_events
ActiveRecord::PreparedStatementInvalid: wrong number of bind variables (1 for 2) in: close = ? OR close IS ?
could one kindly advise me how i write the scope for this correctly
Your scope should be:
scope :expired_or_closed, -> { where("close = true OR date < ?", DateTime.now) }
Or using Arel
scope :expired_or_closed, -> { where(arel_table[:close].eq(true).or(arel_table[:date].lt(DateTime.now)) }
Note that I use expired_or_closed not expired_or_closed_events, because we are defining this scope in Event model, using `events' is redundant.
Use This
scope :expired_or_closed_events, -> { where( "close == ? || date < ? ", true, Date.current ) }
I think your condition should be **close == ? **
otherwise no sense of condition, which always calculate as true
Related
In Rails app, I have the following part of the schema defined:
# frozen_string_literal: true
module Types
module KVInfo
def self.kv_value_scalar(typename, raw_type: String, typeid:)
clazz = Class.new(BaseObject) do
graphql_name "KVEntry#{typename}Value"
field :value, raw_type, null: false
end
clazz.define_singleton_method(:typeid) { typeid }
clazz.define_singleton_method(:typename) { typename }
clazz
end
# typeids taken from enum in (.../kv_info.ts)
KVScalars = [
kv_value_scalar('String', typeid: 0),
kv_value_scalar('Markdown', typeid: 1),
kv_value_scalar(
'Date',
raw_type: GraphQL::Types::ISO8601DateTime,
typeid: 2
),
kv_value_scalar('Country', typeid: 3),
kv_value_scalar('Address', typeid: 5)
].freeze
KVScalars.each { |t| KVInfo.const_set(t.graphql_name, t) }
class KVScalarValue < BaseUnion
possible_types(*KVScalars)
def self.resolve_type(obj, _ctx)
KVScalars.select { |t| t.typeid == obj['type'] }.first
end
end
def self.kv_value_array(subtype)
clazz = Class.new(BaseObject) do
graphql_name "KVEntryArray#{subtype.typename}"
field :value, [subtype], null: false
end
clazz.define_singleton_method(:sub_typeid) { subtype.typeid }
clazz
end
KVArrays = KVScalars.map { |s| kv_value_array(s) }
KVArrays.each { |t| KVInfo.const_set(t.graphql_name, t) }
class KVArrayValue < BaseUnion
possible_types(*KVArrays)
def self.resolve_type(obj, _ctx)
KVArrays.select { |t| t.sub_typeid == obj['subtype'] }
end
end
class KVValue < BaseUnion
# PP HERE
possible_types(KVArrayValue, KVScalarValue)
def self.resolve_type(obj, _ctx)
obj['type'] == 4 ? # typeid for array
KVArrayValue :
KVScalarValue
end
end
class KVEntry < BaseObject
field :name, String, null: false
field :value, KVValue, null: false
end
end
end
While running a Rake task that dumps the whole schema to a file to be consumed by frontend, I see the type denoted by KVEntry class having only the name field.
If I put all possible types in the KVValue class like such:
pp(*KVScalars, *KVArrays)
possible_types(*KVScalars, *KVArrays)
it works and generates types correctly.
But note the pp line above - it does not work without this line (???).
Also, if I keep it as is (with nested unions), it does not work regardless of number and positions of pp clauses. When going through with the debugger, all classes are loaded correctly, including generated ones, but the schema still lacks required types.
So the question is what the bisq... why the types are not processed and how can pp affect this process in any sense?
P.S. The data format is fixed by frontend and no way subject to change.
The problem was in the nested unions. GraphQL does not support these. And on the part of plain union not working - I still have no idea of reasons for such behavior, but it fixed itself after N-th restart.
I am trying to write a rather complicated query using baby_squeel. The query requires the use of the coalesce SQL function. coalesce is used as an example a couple of times on the baby_squeel home page but when I try to use it in a query I get a no method error.
Example below:
result = Table.selecting { |t| [t.col1,
((coalesce(t.col2, 0) + coalesce(t.col3, 0)).sum.as('column'))] }
.where.has { |t| t.col4 == 'some condition' }
.grouping { |t| t.col1 }
I am using Rails 5 and baby_squeel 1.2. The query is called inside of a private controller function.
Why is this happening? Do I need to require something or define the function myself using arel?
Not sure if this will help anyone, but I found what I was missing. Since I gave arity to the block I had to reference the functions I wanted to use with the airty variable in this case t. The correct code is:
result = Table.selecting { |t| [t.col1,
((t.coalesce(t.col2, 0) + t.coalesce(t.col3, 0)).sum.as('column'))] }
.where.has { |t| t.col4 == 'some condition' }
.grouping { |t| t.col1 }
I can not write a valid request to obtain such a result (group recording day):
date (days) - sum (field1) - sum (field2)
date (days) - sum (field1) - sum (field2)
etc.
My code:
document has_many downloads
download belongs_to document
#downloads = Download
.order(created_at: :desc)
.includes(:document)
.joins(:document)
.where('documents.uploaded_by = ?', params[:user_id])
.page(params[:page])
I would be grateful for the help
UPD:
create_table "document_downloads", force: :cascade do |t|
t.integer "document_id", null: false
t.integer "payment_sum"
t.datetime "created_at", null: false
end
i want to group like:
payment_sum created_at
150 2015-06-27
120 2015-06-27
I need more information about your table schema but this can be helpful..
Download.select('date(days), sum(field1), sum(field2)')
.joins(:document)
.where('documents.uploaded_by = ?', params[:user_id])
.group('days')
.page(params[:page])
I want to check if a record already exist on database, but I have one json data type field and I need to compare it too.
When I try check using exists? I got the following error:
SELECT 1 AS one FROM "arrangements"
WHERE "arrangements"."deleted_at" IS NULL AND "arrangements"."account_id" = 1
AND "arrangements"."receiver_id" = 19 AND "config"."hardware" = '---
category: mobile
serial: ''00000013''
vehicle:
' AND "arrangements"."recorded" = 't' LIMIT 1
PG::UndefinedTable: ERROR: missing FROM-clause entry for table "config"
LINE 1: ...id" = 1 AND "arrangements"."receiver_id" = 19 AND "config"."...
^
Code that I using to check if a exists:
#arrangement = Arrangement.new({account_id: receiver.account.id, receiver_id: receiver.id, config: params[:config], recorded: true})
if Arrangement.exists?(account_id: #arrangement.account_id, receiver_id: #arrangement.receiver_id, config: #arrangement.config, recorded: #arrangement.recorded)
puts 'true'
end
I already tried:
if Arrangement.exists?(#arrangement)
puts 'true'
end
But always return false
Table:
create_table :arrangements do |t|
t.references :account, index: true
t.references :receiver, index: true
t.json :config, null: false
t.boolean :recorded, default: false
t.datetime :deleted_at, index: true
t.integer :created_by
t.timestamps
end
You cannot compare jsons. Try to compare some jsons values
where("arrangements.config->>'category' = ?", params[:config][:category])
Look in postgresql docs for other JSON functions and operators
This will convert both field(in case it is just json) and the parameter(which will be a json string) to jsonb, and then perform a comparison of everything it contains.
def existing_config?(config)
Arrangement.where("config::jsonb = ?::jsonb", config.to_json).any?
end
I have a condition like:
if connection
if "name" == connection.name
...
end
end
connection may have nil value initially, so I am not able to check if connection && "name" == connection.name
How can I simplify the condition efficiently?
if connection and connection.name == "name"
...
end
unless connection.nil? || connection.name != "name"
#...Statements
end