Related
I have a product image modal
class ProductImage < ApplicationRecord
belongs_to :product
has_many_attached :images do |attachable|
attachable.variant :thumb, resize_to_limit: [100, nil]
end
def attachement_path
Rails.application.routes.url_helpers.rails_representation_url(
images.first, only_path: true
)
end
def attachement_thumb_path
Rails.application.routes.url_helpers.rails_representation_url(
images.first.variant(:thumb).processed, only_path: true
)
end
end
It perfectly generates attachement_path and display the Image but in case of attachement_thumb_path
It throws the following errors
ActiveStorage::Blob Create (0.4ms) INSERT INTO "active_storage_blobs" ("key", "filename", "content_type", "metadata", "byte_size", "checksum", "created_at", "service_name") VALUES ($1, $2, $3, $4, $5, $6, $7, $8) RETURNING "id" [["key", "uk368qdr9oq73hdg13mdkicpdwb6"], ["filename", "look15.jpg"], ["content_type", "image/jpeg"], ["metadata", "{\"identified\":true}"], ["byte_size", 14510], ["checksum", "f8/qGVxgNbeK3YZ7t/e/HQ=="], ["created_at", "2022-10-26 11:38:41.592281"], ["service_name", "local"]]
ActiveStorage::Attachment Create (0.8ms) INSERT INTO "active_storage_attachments" ("name", "record_id", "record_type", "blob_id", "created_at") VALUES ($1, $2, $3, $4, $5) RETURNING "id" [["name", "image"], ["record_id", nil], ["record_type", "ActiveStorage::VariantRecord"], ["blob_id", "495f44bb-1b19-4279-8331-d7c8d86758f8"], ["created_at", "2022-10-26 11:38:41.593878"]]
TRANSACTION (0.2ms) ROLLBACK
/Users/apple/.rbenv/versions/3.1.2/lib/ruby/gems/3.1.0/gems/activerecord-7.0.4/lib/active_record/connection_adapters/postgresql_adapter.rb:768:in `exec_params': PG::NotNullViolation: ERROR: null value in column "record_id" of relation "active_storage_attachments" violates not-null constraint (ActiveRecord::NotNullViolation)
DETAIL: Failing row contains (49bcc6c0-4167-42f4-8687-a245847798ad, image, null, ActiveStorage::VariantRecord, 495f44bb-1b19-4279-8331-d7c8d86758f8, 2022-10-26 11:38:41.593878).
/Users/apple/.rbenv/versions/3.1.2/lib/ruby/gems/3.1.0/gems/activerecord-7.0.4/lib/active_record/connection_adapters/postgresql_adapter.rb:768:in `exec_params': ERROR: null value in column "record_id" of relation "active_storage_attachments" violates not-null constraint (PG::NotNullViolation)
DETAIL: Failing row contains (49bcc6c0-4167-42f4-8687-a245847798ad, image, null, ActiveStorage::VariantRecord, 495f44bb-1b19-4279-8331-d7c8d86758f8, 2022-10-26 11:38:41.593878).
irb(main):003:0>
If I remove the null: false validation from record column of active_storage_attachments table everything works perfectly But since this table is generated by action storage I dont want to modify it.
I am passing an array of ids to a .where in Rails, but the way it's returned doesn't preserve the order. For example, here's the array:
2.5.1 :043 > company_ids
=> [83, 79, 52, 44, 82]
I am looking for all pages that have those company IDs, but returned in the order of those company IDs that were provided. This is the result if I try to compare:
2.5.1 :044 > Page.where(company_id: company_ids).pluck(:company_id)
(1.1ms) SELECT "pages"."company_id" FROM "pages" WHERE "pages"."company_id" IN ($1, $2, $3, $4, $5) [["company_id", 83], ["company_id", 79], ["company_id", 52], ["company_id", 44], ["company_id", 82]]
=> [83, 82, 52, 44, 79]
I ran across this stackoverflow post (ActiveRecord.find(array_of_ids), preserving order) that seems to provide a solution, but it doesn't work for me. When trying to use Page.where(company_id: company_ids).order("field(company_id, #{company_ids.join ','})") as suggested in the stackoverflow post, I get the following error:
2.5.1 :042 > Page.where(company_id: company_ids).order("field(company_id, #{company_ids.join ','})")
Page Load (2.0ms) SELECT "pages".* FROM "pages" WHERE "pages"."company_id" IN ($1, $2, $3, $4, $5) ORDER BY field(company_id, 83,79,52,44,82) LIMIT $6 [["company_id", 83], ["company_id", 79], ["company_id", 52], ["company_id", 44], ["company_id", 82], ["LIMIT", 11]]
Traceback (most recent call last):
ActiveRecord::StatementInvalid (PG::UndefinedFunction: ERROR: function field(bigint, integer, integer, integer, integer, integer) does not exist)
LINE 1: ...ts"."company_id" IN ($1, $2, $3, $4, $5) ORDER BY field(comp...
^
HINT: No function matches the given name and argument types. You might need to add explicit type casts.
: SELECT "pages".* FROM "pages" WHERE "pages"."company_id" IN ($1, $2, $3, $4, $5) ORDER BY field(company_id, 83,79,52,44,82) LIMIT $6
I just simply want to call Pages.where(company_id: company_ids) and get the pages back based on order of company_ids that was provided.
As a workaround, I am using this:
company_ids = companies.order("full_name ASC").pluck(:id)
pages = []
company_ids.each {|c| pages << Page.find_by(company_id: c)}
but seems like that would be inefficient if there are thousands of records. or even just hundreds.
The problem is you're using a MySQL function (field), but the RDBMS you're using is PostgreSQL.
You can try with position, using the row company_id and the array of ids concatenated:
Page.where(company_id: company_ids).order("position(company_id::text in '#{ids.join(',')}')")
Use:
Page.where(company_id: company_ids).order(Arel.sql("position(company_id::text in '#{ids.join(',')}')"))
if you're getting a deprecation warning.
There also exists the possibility to use find, which as stated in the doc says The returned records are in the same order as the ids you provide. Although I don't know if it applies for your case.
I've never had this before, but somehow when I'm combining a date and a time to a concatenated datetime and store it in the db, I'm off by 2 hours. I just noticed when I started using time_ago_in_words, it's always two hours from now when I just saved something new.
Any idea how to overcome this differnece. I think this is the code that's responsible for the difference:
def create_timestamp
self.date = day.to_datetime + time.seconds_since_midnight.seconds
end
In case anyone is wondering, I'm using a seperate date & time picker on my form, so this the before_save method to create one timestamp for the user input.
Upon request, the SQL for an INSERT at 10:47 CEST, Rails app is in UTC btw:
INSERT INTO "reports" ("account_id", "description", "report_category_id", "day", "time", "user_id", "date", "created_at", "updated_at") VALUES ($1, $2, $3, $4, $5, $6, $7, $8, $9) RETURNING "id" [["account_id", 2], ["description", ""], ["report_category_id", 4], ["day", "2016-07-30"], ["time", "2000-01-01 10:47:00.000000"], ["user_id", 1], ["date", "2016-07-30 10:47:00.000000"], ["created_at", "2016-07-30 08:47:53.828175"], ["updated_at", "2016-07-30 08:47:53.828175"]]
I'm tried to create a User in the console doing:
2.2.1 :012 > u.save!
(0.2ms) BEGIN
User Exists (0.7ms) SELECT 1 AS one FROM "users" WHERE LOWER("users"."email") = LOWER('noc#co.co') LIMIT 1
SQL (2.1ms) INSERT INTO "users" ("id", "first_name", "last_name", "email", "title", "time_zone", "company_id", "password_digest", "created_at", "updated_at", "activation_digest") VALUES ($1, $2, $3, $4, $5, $6, $7, $8, $9, $10, $11) RETURNING "id" [["id", 200], ["first_name", "Random"], ["last_name", "Dude"], ["email", "noc#co.co"], ["title", "CEO"], ["time_zone", "Stockholm"], ["company_id", 1], ["password_digest", "$2a$10$bHHA/JP5IMrucGUXRWMpsO8sInaouSqn48M.fDHpjGdvedu3Napra"], ["created_at", "2015-10-11 23:09:38.213109"], ["updated_at", "2015-10-11 23:09:38.213109"], ["activation_digest", "$2a$10$WF3bUOtbC1gk4ZnX58cJZO5k7P7YV6wvhmwz7EErTdvIseNuy0oyq"]]
2.2.1 :013 > u.activation_token
=> "vKrs0jtvZRiyU-YVE-aPXw"
now when I try to create a user the before_create doesn't work, I tried changing it to before_validation and that didn't work either.
The user is a nested attribute from companies, and is created in Companies#new.
class User < ActiveRecord::Base
belongs_to :company
attr_accessor :remember_token, :activation_token, :reset_token
before_save :downcase_email
before_create :create_activation_digest
now when I do #user.activation_token it returns nil. Here's the console log from when I try it on the app:
Started POST "/companies" for ::1 at 2015-10-12 01:31:47 +0200
Processing by CompaniesController#create as HTML
Parameters: {"utf8"=>"✓", "authenticity_token"=>"ZTEtGR2Dd1FDDYm9j4/SiqSTP646R8gctFx4aJHM9QDP+RQky8SG6gkomLbf+E+LgMi+aah1YOhCkUsg3uSYoQ==", "company"=>{"time_zone"=>"Stockholm", "users_attributes"=>{"0"=>{"first_name"=>"swaga", "last_name"=>"swaga", "email"=>"swaga#wkoa.com", "password"=>"[FILTERED]"}}, "name"=>"swaga"}, "commit"=>"Create Company"}
(0.2ms) BEGIN
User Exists (1.3ms) SELECT 1 AS one FROM "users" WHERE LOWER("users"."email") = LOWER('swaga#wkoa.com') LIMIT 1
SQL (7.1ms) INSERT INTO "companies" ("name", "time_zone", "created_at", "updated_at") VALUES ($1, $2, $3, $4) RETURNING "id" [["name", "swaga"], ["time_zone", "Stockholm"], ["created_at", "2015-10-11 23:31:47.380530"], ["updated_at", "2015-10-11 23:31:47.380530"]]
SQL (0.5ms) INSERT INTO "users" ("first_name", "last_name", "email", "password_digest", "activation_digest", "company_id", "created_at", "updated_at") VALUES ($1, $2, $3, $4, $5, $6, $7, $8) RETURNING "id" [["first_name", "swaga"], ["last_name", "swaga"], ["email", "swaga#wkoa.com"], ["password_digest", "$2a$10$3GsPACTg5HPodiqdedsCvu52N64BEE3/fA77p.oBHAhM51zCSzUV."], ["activation_digest", "$2a$10$75y9jP.eZxmWI1KjHZrg3.DuB5GSwiS2UsaQdtV25ClBHDi.z4Pte"], ["company_id", 8], ["created_at", "2015-10-11 23:31:47.390462"], ["updated_at", "2015-10-11 23:31:47.390462"]]
(6.7ms) COMMIT
User Load (0.9ms) SELECT "users".* FROM "users" WHERE "users"."company_id" = $1 ORDER BY "users"."id" ASC LIMIT 1 [["company_id", 8]]
Rendered user_mailer/account_activation.html.erb within layouts/mailer (7.8ms)
UserMailer#account_activation: processed outbound mail in 29.2ms
Completed 500 Internal Server Error in 380ms (ActiveRecord: 16.9ms)
ActionController::UrlGenerationError - No route matches {:action=>"edit", :controller=>"account_activations", :email=>"swaga#wkoa.com", :id=>nil} missing required keys: [:id]:
now I see that the activation_digest is returned, so I think the issue is literarily just the before_create not working? Which is weird because then it shouldn't be able to create an activation digest as the two are connected:
# Creates and assigns the activation token and digest.
def create_activation_digest
self.activation_token = User.new_token
self.activation_digest = User.digest(activation_token)
end
Your error says:
ActionController::UrlGenerationError - No route matches {:action=>"edit", :controller=>"account_activations", :email=>"swaga#wkoa.com", :id=>nil} missing required keys: [:id]:
Seems like, in your view, you are calling edit_account_activation_path without the id param and that's creating the problem for you. Try to send the user.id as a parameter in the edit_account_activation_path call.
Something like this:
edit_account_activation_path(user.email, user.id)
That should fix your issue.
My app has started throwing errors when I try to save a particular class to the database. I'm not sure exactly what caused this to start happening - I've been having all kinds of database issues for the last few days....
In any case, my model seems to be working fine (it is properly calculating all of the before_save values), but then it tries to save to the database and blows up.
SQL (0.8ms) INSERT INTO "portfolios" ("correlation_matrix", "created_at", "data", "mean_return", "std_dev", "updated_at", "weights") VALUES ($1, $2, $3, $4, $5, $6, $7) RETURNING "id" [["correlation_matrix", "--- \n- - 1.0\n - -0.4873114574375062\n- - -0.4873114574375062\n - 1.0\n"], ["created_at", Sat, 16 Jun 2012 15:12:35 MDT -06:00], ["data", {"TSX"=>0.5, "VUSTX"=>0.5}], ["mean_return", #<BigDecimal:7fadb119b750,'0.488052381E-1',18(45)>], ["std_dev", #<BigDecimal:7fadb119b598,'0.7668705159 123244E-1',18(45)>], ["updated_at", Sat, 16 Jun 2012 15:12:35 MDT -06:00], ["weights", "--- \nTSX: 0.5\nVUSTX: 0.5\n"]]
Throws this error:
ActiveRecord::StatementInvalid: PG::Error: ERROR: Syntax error near 'T' at position 5
I have no idea what this error means (or what this 'T' is.....), or even where to begin troubleshooting it.... Any help would be appreciated.
I can post whatever information might be necessary to figure this out....
Relevant migration:
create_table :portfolios do |t|
t.text :weights
t.decimal :mean_return, :precision => 15, :scale => 10
t.decimal :std_dev, :precision => 15, :scale => 10
t.text :correlation_matrix
t.hstore :data
t.timestamps
end
execute "CREATE INDEX portfolios_gin_data_hstore ON portfolios USING GIN(data);"
Full stack trace:
ActiveRecord::StatementInvalid: PG::Error: ERROR: Syntax error near 'T' at position 5
: INSERT INTO "portfolios" ("correlation_matrix", "created_at", "data", "mean_return", "std_dev", "updated_at", "weights") VALUES ($1, $2, $3, $4, $5, $6, $7) RETURNING "id"
from /Users/brandon/.rvm/gems/ruby-1.9.3-p194#myapp/gems/activerecord-3.2. 6/lib/active_record/connection_adapters/postgresql_adapter.rb:1164:in `get_last_result'
from /Users/brandon/.rvm/gems/ruby-1.9.3-p194#myapp/gems/activerecord-3.2. 6/lib/active_record/connection_adapters/postgresql_adapter.rb:1164:in `exec_cache'
from /Users/brandon/.rvm/gems/ruby-1.9.3-p194#myapp/gems/activerecord-3.2. 6/lib/active_record/connection_adapters/postgresql_adapter.rb:665:in `block in exec_query'
from /Users/brandon/.rvm/gems/ruby-1.9.3-p194#myapp/gems/activerecord-3.2. 6/lib/active_record/connection_adapters/abstract_adapter.rb:280:in `block in log'
from /Users/brandon/.rvm/gems/ruby-1.9.3-p194#myapp/gems/activesupport-3.2.6/lib/active_support/notifications/instrumenter. rb:20:in `instrument'
from /Users/brandon/.rvm/gems/ruby-1.9.3-p194#myapp/gems/activerecord-3.2. 6/lib/active_record/connection_adapters/abstract_adapter.rb:275:in `log'
from /Users/brandon/.rvm/gems/ruby-1.9.3-p194#myapp/gems/activerecord-3.2. 6/lib/active_record/connection_adapters/postgresql_adapter.rb:663:in `exec_query'
from /Users/brandon/.rvm/gems/ruby-1.9.3-p194#myapp/gems/activerecord-3.2. 6/lib/active_record/connection_adapters/abstract/database_statements.rb:63:in `exec_insert'
from /Users/brandon/.rvm/gems/ruby-1.9.3-p194#myapp/gems/activerecord-3.2. 6/lib/active_record/connection_adapters/abstract/database_statements.rb:90:in `insert'
from /Users/brandon/.rvm/gems/ruby-1.9.3-p194#myapp/gems/activerecord-3.2. 6/lib/active_record/connection_adapters/abstract/query_cache.rb:14:in `insert'
from /Users/brandon/.rvm/gems/ruby-1.9.3-p194#myapp/gems/activerecord-3.2.6/lib/active_record/relation.rb:66:in `insert'
from /Users/brandon/.rvm/gems/ruby-1.9.3-p194#myapp/gems/activerecord-3.2.6/lib/active_record/persistence.rb:363:in `create'
from /Users/brandon/.rvm/gems/ruby-1.9.3-p194#myapp/gems/activerecord-3.2.6/lib/active_record/timestamp.rb:57:in `create'
from /Users/brandon/.rvm/gems/ruby-1.9.3-p194#myapp/gems/activerecord-3.2.6/lib/active_record/callbacks.rb:268:in `block in create'
from /Users/brandon/.rvm/gems/ruby-1.9.3-p194#myapp/gems/activesupport-3.2.6/lib/active_support/callbacks.rb:403:in `_run__772785567275930853__create__1186465801021498362__callbacks'
from /Users/brandon/.rvm/gems/ruby-1.9.3-p194#myapp/gems/activesupport-3.2.6/lib/active_support/callbacks.rb:405:in `__run_callback'
... 11 levels...
from /Users/brandon/.rvm/gems/ruby-1.9.3-p194#myapp/gems/activerecord-3.2.6/lib/active_record/validations.rb:50:in `save'
from /Users/brandon/.rvm/gems/ruby-1.9.3-p194#myapp/gems/activerecord-3.2.6/lib/active_record/attribute_methods/dirty.rb:22:in `save'
from /Users/brandon/.rvm/gems/ruby-1.9.3-p194#myapp/gems/activerecord-3.2.6/lib/active_record/transactions.rb:241:in `block (2 levels) in save'
from /Users/brandon/.rvm/gems/ruby-1.9.3-p194#myapp/gems/activerecord-3.2.6/lib/active_record/transactions.rb:295:in `block in with_transaction_returning_status'
from /Users/brandon/.rvm/gems/ruby-1.9.3-p194#myapp/gems/activerecord-3.2. 6/lib/active_record/connection_adapters/abstract/database_statements.rb:192:in `transaction'
from /Users/brandon/.rvm/gems/ruby-1.9.3-p194#myapp/gems/activerecord-3.2.6/lib/active_record/transactions.rb:208:in `transaction'
from /Users/brandon/.rvm/gems/ruby-1.9.3-p194#myapp/gems/activerecord-3.2.6/lib/active_record/transactions.rb:293:in `with_transaction_returning_status'
from /Users/brandon/.rvm/gems/ruby-1.9.3-p194#myapp/gems/activerecord-3.2.6/lib/active_record/transactions.rb:241:in `block in save'
from /Users/brandon/.rvm/gems/ruby-1.9.3-p194#myapp/gems/activerecord-3.2.6/lib/active_record/transactions.rb:252:in `rollback_active_record_state!'
from /Users/brandon/.rvm/gems/ruby-1.9.3-p194#myapp/gems/activerecord-3.2.6/lib/active_record/transactions.rb:240:in `save'
from (irb):33
from /Users/brandon/.rvm/gems/ruby-1.9.3-p194#myapp/gems/railties-3.2.6/lib/rails/commands/console.rb:47:in `start'
from /Users/brandon/.rvm/gems/ruby-1.9.3-p194#myapp/gems/railties-3.2.6/lib/rails/commands/console.rb:8:in `start'
from /Users/brandon/.rvm/gems/ruby-1.9.3-p194#myapp/gems/railties-3.2.6/lib/rails/commands.rb:41:in `<top (required)>'
from script/rails:6:in `require'
from script/rails:6:in `<main>'
UPDATE 1
Some model code as requested.
macro stuff:
attr_accessible :weights
serialize :correlation_matrix
serialize :weights
has_and_belongs_to_many :securities, :uniq => true
has_and_belongs_to_many :efficient_frontiers
before_validation :format_weights_tickers, :add_securities, :validate_weights, :set_weights_in_hstore, :build_correlation_matrix, :set_mean_return, :set_standard_deviation
validates_presence_of :mean_return, :std_dev, :securities, :correlation_matrix, :weights
validates_numericality_of :mean_return, :std_dev
validate :uniqueness_of_weights
before_destroy :check_for_dependent
scope :by_std_dev, :order => 'std_dev ASC'
anything and everything I can find to do with the HStore column
all I really use HStore for is for a search on specific tickers. This used to work... I don't know what changed. I might have upgraded Postgres (I was fiddling around with homebrew) or potentially something changed with rails. I did try going back to 3.2.3 but I got the same error.
def self.find_by_hstore(search_key, search_value)
where("data #> (:key => :value)", :key => search_key.to_s, :value => search_value.to_s)
end
def set_weights_in_hstore
self.data = {} if self.data.nil?
weights.each_pair {|ticker, weight| self.data[ticker.to_s] = weight}
end
I can post the entirety of the model if this is too disjointed. Let me know!
UPDATE #2 - I am getting similar errors elsewhere also....
After a simple user signup....
SQL (10.9ms) INSERT INTO "users" ("admin", "confirmation_sent_at", "confirmation_token", "confirmed_at", "created_at", "current_sign_in_at", "current_sign_in_ip", "data", "email", "encrypted_password", "last_email_at", "last_sign_in_at", "last_sign_in_ip", "name", "plan", "remember_created_at", "reset_password_sent_at", "reset_password_token", "selected_portfolio_id", "sign_in_count", "unconfirmed_email", "updated_at", "verified") VALUES ($1, $2, $3, $4, $5, $6, $7, $8, $9, $10, $11, $12, $13, $14, $15, $16, $17, $18, $19, $20, $21, $22, $23) RETURNING "id" [["admin", false], ["confirmation_sent_at", Sat, 16 Jun 2012 20:37:07 MDT -06:00], ["confirmation_token", "7Xu15pMrV9zTNmofv8bD"], ["confirmed_at", nil], ["created_at", Sat, 16 Jun 2012 20:37:07 MDT -06:00], ["current_sign_in_at", nil], ["current_sign_in_ip", nil], ["data", {"min_rebalance_spacing"=>90 days, "max_contact_frequency"=>7 days, "allowable_drift"=>5}], ["email", "joe#what.com"], ["encrypted_password", "$2a$10$HNUmlYmcVXbBsyZRFCAB7e8c5mf6S9UOdWr/ZCz10y5Sg4gOh8Zvq"], ["last_email_at", Sat, 16 Jun 2012 20:37:07 MDT -06:00], ["last_sign_in_at", nil], ["last_sign_in_ip", nil], ["name", "Joe Blow"], ["plan", "basic"], ["remember_created_at", nil], ["reset_password_sent_at", nil], ["reset_password_token", nil], ["selected_portfolio_id", nil], ["sign_in_count", 0], ["unconfirmed_email", nil], ["updated_at", Sat, 16 Jun 2012 20:37:07 MDT -06:00], ["verified", false]]
20:37:07 log.1 | [ef4a7d55fb30e8fb82ac6c860e674bfc] [127.0.0.1] PG::Error: ERROR: Syntax error near 'm' at position 5
20:37:07 log.1 | : INSERT INTO "users" ("admin", "confirmation_sent_at", "confirmation_token", "confirmed_at", "created_at", "current_sign_in_at", "current_sign_in_ip", "data", "email", "encrypted_password", "last_email_at", "last_sign_in_at", "last_sign_in_ip", "name", "plan", "remember_created_at", "reset_password_sent_at", "reset_password_token", "selected_portfolio_id", "sign_in_count", "unconfirmed_email", "updated_at", "verified") VALUES ($1, $2, $3, $4, $5, $6, $7, $8, $9, $10, $11, $12, $13, $14, $15, $16, $17, $18, $19, $20, $21, $22, $23) RETURNING "id"
UDPATE 3
There appears to be something funky going on with my database / user table. I get the following error during loading the environment in a migration:
rake aborted!
PG::Error: ERROR: relation "users" does not exist
LINE 4: WHERE a.attrelid = '"users"'::regclass
^
: SELECT a.attname, format_type(a.atttypid, a.atttypmod), d.adsrc, a.attnotnull
FROM pg_attribute a LEFT JOIN pg_attrdef d
ON a.attrelid = d.adrelid AND a.attnum = d.adnum
WHERE a.attrelid = '"users"'::regclass
AND a.attnum > 0 AND NOT a.attisdropped
ORDER BY a.attnum
I just had a similar problem, on Rails 3.2. If you're not using Rails trunk (working towards 4.0), it doesn't understand the hstore natively - you need to define a serialization coder (which is provided by the activerecord-postgres-hstore gem), like so:
class Example < ActiveRecord::Base
serialize :data, ActiveRecord::Coders::Hstore
end