4,900 questions
1
vote
1
answer
130
views
How to exit around_save callback before executing yield block
Currently upgrading an app from Rails 4 to Rails 5.2.
I'm trying to determine how you handle the around_save callback, where you want to exit based on logic, before you execute the block.
When using a ...
0
votes
1
answer
121
views
Rails 7.2 PG::InvalidTextRepresentation with integer column & binding
We are planning the migration to Rails 7.2.2.1 (we currently run on 7.1.5.1).
We have noticed some errors during the CI run while querying with binding variable on integer column.
For example :
# ...
0
votes
1
answer
86
views
How to get to polymorphic grandchildren in Rails ActiveRecord
I have an entity that has invoices and offers.
class Entity < ApplicationRecord
has_many :invoices, dependent: :restrict_with_error
has_many :offers, dependent: :restrict_with_error
Invoices ...
0
votes
1
answer
169
views
How to automatically load model schema on rails console start?
I have a configuration in .irbrc that would auto connect to the database when loading rails console:
# ~/.irbrc
if defined? Rails
# connect to db to avoid seeing `User (call 'User.connection' to ...
0
votes
0
answers
122
views
Ruby on Rails Sidekiq Worker doesn't complete process, but no error is shown - Processing 30,000+ records in batches
I’m facing an issue with a Sidekiq worker that processes a large number of records in batches, but it’s not completing the process correctly. The worker starts executing, but never reaches the "...
0
votes
1
answer
245
views
"This connection is in use by Fiber" error after upgrade to rails 7.2 and ruby 3.2.2
We meet error after app upgrade to rails 7.2 and ruby 3.2.2.
ActiveRecord::StatementInvalid Mysql2::Error: This connection is in use by: #<Fiber:0x00007fad145210e8 (resumed)>
It is occurred in ...
0
votes
0
answers
55
views
Get version of model before it was saved?
I have a Sidekiq Job that syncs one of my models to an external source. This is a - let's say expensive - operation, that I would like to run only when needed. Reading the current state of the ...
1
vote
2
answers
213
views
Possible to remove method in ActiveRecord?
Context: Rails 7.1, only using the DB interaction layers, no web framework, no servers, etc...
I'm sure this is going to ruffle a few feathers, but I keep running into ActiveRecord::...
0
votes
0
answers
78
views
How do I use multiple small sqlite databases as secondary datasource for storing measurements by devices?
I have set up a database that stores measurement data for thousands of IoT devices. The table storing measurements (using foreign keys to link with devices) quickly became HUGE and performance dropped,...
0
votes
1
answer
185
views
How to encrypt plain text in such a way that encryption will matched with our saved record encryption?
The problem is that let say I have a model called Propose and i use Active Record Encryption to encrypt some attributes as shown in below code:
class Propose < ApplicationRecord
encrypts :email, :...
0
votes
0
answers
119
views
Problem with ActiveRecord-Session_store gem when starting up Rails 6 app
I'm upgrading a Rails app from v5 to v6.1.7 (ruby:2.7.7), but I have a problem with active_record_store for sessions at start up when running locally in Docker.
I've installed the 'activerecord-...
0
votes
0
answers
59
views
Triggering an explicit state-machine event in a before_ filter
I have an ActiveRecord model using the state-machines gem.
In it, I wish to trigger an event in a before_validation or before_save callback:
class Model < ApplicationRecord
state_machine initial: ...
0
votes
1
answer
84
views
List all associations of a model
I'm looking for a way to list all associations of a model. This is to run some consistency background validation of the big and old database. Too many models to manually discover them and error prone.
...
0
votes
1
answer
48
views
Rails ActiveModel get sum of calculated column
How can I perform calculations on calculated columns in ActiveRecord?
I have a model Position
class Position < ApplicationRecord
belongs_to :invoice
belongs_to :vat_type
end
The following ...
1
vote
1
answer
79
views
Saving an associated polymorphic object duplicates it
I have two models, one of them being polymorphic and second one being a "parent" one:
class Person
has_one :asset, as: :assetable
accepts_nested_attributes_for :asset
end
class Asset
...
0
votes
1
answer
354
views
Upsert_all with uniqueness index constraint
I'm facing a dilemma.
I've created a model with an wave_order column with uniqueness db index with wavable. wavable is a polymorphic (but we don't care actually).
# migration
create_table :...
0
votes
1
answer
110
views
How to set timezone for ActiveRecord queries to fetch the accurate figures?
I am building a Rails 7 app that is targetted for the German audience.
My current local German time is Fri Jun 21 12:10:23 CEST 2024 (output from date in terminal). When I log in to my production ...
0
votes
3
answers
98
views
How to Allow nil Description in Rails STI Special Model Without Modifying Parent Model Validations?
Premise:
Developing an application using Rails.
There is a Book model.
Derived from Book, there are NormalBook and SpecialBook models for STI.
The Book model has a description field with a presence: ...
-1
votes
1
answer
81
views
How do I eager load multiple associations in same query with ActiveRecord?
Given the following:
Project has_many collectors
Collector has_one gs_collector
GsCollector has_one model
Model has a field named title
How do I in one query get all the model titles inside any one ...
1
vote
1
answer
239
views
Trouble Getting sqlite3 gem to load in AR command-line app
I am writing a command-line app that uses active_record for database interactions. I currently support only postgres, but I want to allow sqlite3 as well. I added a line to my gemspec file to add ...
0
votes
1
answer
46
views
Do I need to use Class.scope_name when using scope in the same model, or can I just use scope_name?
class User < ApplicationRecord
scope :active, -> { where(active: true) }
def some_method_in_user_model
users = active # -> is this right or
users = User.active # is this right?
...
1
vote
2
answers
129
views
Rails. Validation with has_many through: association
I’m working on a Rails 7 application with the following models and associations.
For example, there are models and associations:
class Article < ApplicationRecord
has_many :article_classifiers
...
0
votes
4
answers
123
views
How to write Rails scope for this SQL query
I have an issue to get rows from database by multiple conditions.
I have a table Slot and SlotAlteration.
The slot has a time_off_id field.
SlotAlteration has two columns, slot_id and action. Action ...
0
votes
1
answer
60
views
Rails many-to-many association query by AND of associated records
I have a Rails project with a Product model and a Feature model and a many-to-many relationship between them as follows:
# == Schema Information
#
# Table name: products
#
# id ...
2
votes
1
answer
130
views
How to check if a Rails model is defined? [duplicate]
I'm using a Ruby on Rails 5.2.8 and Ruby 2.7.8 version and I have found a bug in code. The code should check at runtime if a model is defined. At first I tried to use the defined? method, but because ...
0
votes
2
answers
78
views
Subbing a class name for a table name in ActiveRecord query
I've got this line:
factory.workers.where.not(confirmed_at:nil).where(job_roles: {heavy_lifting:true, sensitive_area: false}).pluck(:work_capacity)
But the association table job_roles depends on the ...
0
votes
1
answer
159
views
Enum, default value reseted to nil on save
In a RoR 7.1.3 application using PostgreSQL, I've a enum defined as:
create_enum :foo_states, %i[active inactive]
create_table :foo do |t|
t.enum :state, enum_type: :foo_states, default: :active, ...
2
votes
1
answer
99
views
How to insert a bare null jsonb value to Postgres table field in Ruby on Rails via ActiveRecord?
Here is an SQL snippet:
CREATE TABLE jsonb_null (
id bigserial PRIMARY KEY,
value jsonb
);
INSERT INTO jsonb_null (value) VALUES ('"null"'), ('null'), (NULL);
SELECT id, value, ...
0
votes
1
answer
50
views
Is there a way to create a has_many association that just filters items from another has_many association?
Basically I have a has_many association. I want to create another association that just filters items from the original association.
class Track
belongs_to :playlist
end
class Playlist
has_many :...
0
votes
1
answer
419
views
Rails Active Record Statement Invalid Undefined column
I'm completely new in using ruby on rails and active record.
I cant seem to figure out why I keep getting this error. I am trying to delete soccer teams through the destroy method and it wont work. ...
0
votes
1
answer
54
views
Rails query working in console but not in the controller
I have an application that has a table Doctors with a name field. The users can put any version of the name in there they want. I'm trying to sort the records based on last name(last word in the ...
0
votes
0
answers
61
views
ActiveRecord validation error: saying field is blank even though it isn't
When I create try to create a new ActiveRecord I get the following error:
Failure/Error: @gallery = Gallery.create!(gallery_picture: ["test"], GeneralInfo_id: 1, gallery_title: "test&...
0
votes
0
answers
57
views
Rails eager loading with WHERE clause results in two SQL queries
I'm trying to eager load a Course model with some associated models, Community and Package. The relationships between them are as follows:
class Community < ApplicationRecord
...
has_many :...
1
vote
1
answer
1k
views
Decrypting Fields Encrypted by Rails Active Record Encryptor in Plain Ruby
I have a Rails application with a table named "orders" containing encrypted fields. The encryption is handled by Rails 7's built-in Active Record Encryption feature.
I'm attempting to write ...
1
vote
3
answers
286
views
How to destroy a bi-directional has_one association from either end?
Here are my models:
class Left < ApplicationRecord
has_one :middle, dependent: :destroy
has_one :right, through: :middle
end
class Middle < ApplicationRecord
belongs_to :left, dependent: :...
1
vote
1
answer
57
views
Why is this Rails collection_select not rendering the association attribute?
Flight - belongs_to :departure_airport, Airport has_many :departing_flights.
I am trying to create a drop down select form element within a Rails form_with where the association's :city value for each ...
2
votes
1
answer
290
views
How can I retry an ActionController action inside a rescue_from for a StaleObjectError
I want to do something like this:
MyController < ApplicationController
rescue_from ActiveRecord::StaleObjectError, :retry
I have an app where users and admins are occasionally updating the same ...
1
vote
1
answer
245
views
Extract records from PostgreSQL based on time of day component of timestamp/DateTime in Rails Active Record
I am working with a PostgreSQL database in a rails application and facing a challenge in extracting the user records on the basis of only the time component from timestamp type created_at column in my ...
1
vote
2
answers
91
views
Rails Active Record, reciprocal dependency hell
I have two models with a 1 to 1 reciprocal dependency.
User (1..1) <-> (1..1) Address
I have set up it like this:
class User
has_one :address
validates :address, presence: true
# ...
0
votes
1
answer
526
views
database_tasks: false not working in rails 7.1
I have 2 read replicas configured in the database.yml and I want to avoid any write operation in the Ruby on Rails application.
When setting database_tasks: false the following exception was raised:
/....
1
vote
1
answer
156
views
Why is my ActiveRecord (v6) `before_destroy` callback not firing?
I have a model where X can contain many Y's, and a Y can contain many Z's. It's a tree -- a child can not belong to more than one parent.
The put statements show me that the before_destroy callback ...
0
votes
2
answers
64
views
Is there a way to create a Ruby model scope for ordering books? (none numeric, none alphabetic)
I have an app where there are quotes from books with notes or thoughts on the quotes. I want to list out the quotes in order of the book order, chapter order and then page order.
Is there a way to ...
0
votes
1
answer
67
views
Ruby ActiveRecord how to avoid Database delay/lock when child record callback is updating parent record
I have a Sidekiq project running a task creates multiple child records and updates the parent record to which this child object belongs. The database is Postgres.
The schema is give below. When the ...
0
votes
1
answer
66
views
How to iterate over ActiveRecord relation through a has_many association
So i've got certain IceCream in which i'd like to get the sales amount in Ontario of low fat ice cream and non expired, say.
IceCream has_many ontario_sales_receipts:
included_ice_cream = IceCream....
1
vote
1
answer
321
views
Error (Could not find the inverse association for profile_image_attachment (:record in ActiveStorage::Attachment)):
In my app/models/active_storage/attachment.rb file I had used this code
class ActiveStorage::Attachment < ApplicationRecord
belongs_to :blob, class_name: "ActiveStorage::Blob
def self....
0
votes
1
answer
95
views
How to rename column in rails through terminal?
I am unable to rename column through terminal
how to rename column in rails without writing anything inside migration file .I meant to say how we can rename column through terminal only.so please give ...
1
vote
1
answer
1k
views
ActiveRecord 7: using writing and reading roles without ORM model classes
I'm working on an application that uses ActiveRecord for database access, but does not use ORM features such as model classes - queries are all made with literal SQL and calls to exec_query.
I'd like ...
0
votes
2
answers
95
views
How to build a dynamic scope in rails
How do i construct a dynamic scope search given a variable-length array of elements to exclude, as in:
class Participant < ApplicationRecord
scope exclude_names, -> (['%name1%', '%name2%', '%...
0
votes
1
answer
74
views
Rails + Query / Scope on ActiveRecord::Relation Not Working
On Rails Console, tried to find some data.
Model: User
class User < ApplicationRecord
scope :active, -> { where(status: true) }
scope :inactive, -> { where(status: false) }
...
0
votes
2
answers
199
views
SQL Syntax error - ActiveRecord::StatementInvalid: PG::SyntaxError: ERROR
I created a method to build an SQL query on Rails, and I'm getting a syntax error, no idea why, the code looks correct to me.
Maybe someone here is able to find the issue? It's likely something pretty ...