How to avoid destroy deleting earlier related object - ruby-on-rails

If the user already has a favorite model after log in, then I want the products that were added to their anonymous bookmarks to be overwritten in the favorite that is attached to their user object.
I find session_favorite (anonymous favorite), #favorite, which belongs to the user. I am rewriting line_item.favorite with the ID of session_favorite to the user's ID favorite. I reset the session and destroy that anonymous favorite, which in theory has become empty, since now line_items has the user's favorite ID.
But, for some reason, when destroying a session_favorite, line_items are also deleted. Why?
module CurrentFavorite
def set_favorite
if user_signed_in?
set_user_favorite
else
if session[:favorite]
#favorite = Favorite.find(session[:favorite])
else
#favorite = Favorite.create
session[:favorite] = #favorite.id
end
end
end
def set_user_favorite
if session[:favorite]
if current_user.favorite.nil?
#favorite = Favorite.find(session[:favorite])
session[:favorite] = nil
#favorite.update(user: current_user)
else
#block with error
session_favorite = Favorite.find(session[:favorite])
#favorite = Favorite.find_by(user: current_user)
session_favorite.line_items.each do |line_item|
line_item.update(favorite: #favorite)
end
session[:favorite] = nil
session_favorite.destroy
#favorite
end
else
if current_user.favorite.nil?
#favorite = current_user.build_favorite
#favorite.save
else
#favorite = Favorite.find_by(user: current_user)
end
end
end
end
LineItem Update (0.7ms) UPDATE "line_items" SET "favorite_id" = ?, "updated_at" = ? WHERE "line_items"."id" = ? [["favorite_id", 1], ["updated_at", "2020-06-07 05:19:54.653064"], ["id", 13]]
↳ app/models/concerns/current_favorite.rb:31
(12.9ms) commit transaction
↳ app/models/concerns/current_favorite.rb:31
(0.0ms) begin transaction
↳ app/models/concerns/current_favorite.rb:31
Movie Load (0.1ms) SELECT "movies".* FROM "movies" WHERE "movies"."id" = ? LIMIT ? [["id", 2], ["LIMIT", 1]]
↳ app/models/concerns/current_favorite.rb:31
LineItem Update (0.7ms) UPDATE "line_items" SET "favorite_id" = ?, "updated_at" = ? WHERE "line_items"."id" = ? [["favorite_id", 1], ["updated_at", "2020-06-07 05:19:54.674229"], ["id", 14]]
↳ app/models/concerns/current_favorite.rb:31
(3.6ms) commit transaction
↳ app/models/concerns/current_favorite.rb:31
(0.0ms) begin transaction
↳ app/models/concerns/current_favorite.rb:34
LineItem Destroy (0.5ms) DELETE FROM "line_items" WHERE "line_items"."id" = ? [["id", 13]]
↳ app/models/concerns/current_favorite.rb:34
LineItem Destroy (0.1ms) DELETE FROM "line_items" WHERE "line_items"."id" = ? [["id", 14]]
↳ app/models/concerns/current_favorite.rb:34
Favorite Destroy (0.2ms) DELETE FROM "favorites" WHERE "favorites"."id" = ? [["id", 10]]
↳ app/models/concerns/current_favorite.rb:34

session_favorite still has the set of line_items associated with it. For performance reasons, Rails does not automatically reload the line_items before destroying the session_favorite so it doesn't recognize that the line_items are now associated with a different favorite.
To prevent the line_items being destroyed, refresh the association before doing the destroy:
session_favorite.line_items.reload
session_favorite.destroy

Related

Rails PUT/POST request fails on first try, works on next

I have a VueJS Frontend application with a Ruby On Rails API backend. I need to change information about a user in the database.
I have a PUT/POST request that removes the creditcard information. The basic rails code is below. The issue I am having is that I get the, very popular, error:
NoMethodError (undefined method []' for nil:NilClass):
But the catch is that it only happens on the first attempt. Subsequent attemps are successful. Can someone point me in the right direction here? Should you need additional informaiton, please don't hesitate to ask.
class AccountsController < ApplicationController
before_action :load_account, only: [:show, :update, :destroy, :formats, :charges, :destroy_card]
def destroy_card
#account.card_last_4 = nil
#account.card_type = nil
#account.card_exp_month = nil
#account.card_exp_year = nil
#account.plan_id = 1
#account.save!
render json: { account: #account }, status: 200
end
private
def load_account
if #current_user.admin?
#account = Account.find(params[:id])
else
#account = #current_user.accounts.find_by_id(params[:id]) unless #account.present?
end
end
end
Errors:
Started PUT "//accounts/20/destroy_card" for ::1 at 2020-08-17 20:24:47 -0400
Processing by AccountsController#destroy_card as */*
Parameters: {"id"=>20, "account_id"=>"20"}
User Load (0.4ms) SELECT `users`.* FROM `users` WHERE `users`.`id` = 10 LIMIT 1
↳ app/controllers/application_controller.rb:18:in `load_user'
AccountUser Load (0.2ms) SELECT `account_users`.* FROM `account_users` WHERE `account_users`.`user_id` = 10 AND `account_users`.`account_id` = 20 LIMIT 1
↳ app/controllers/application_controller.rb:28:in `load_user'
Account Load (0.1ms) SELECT `accounts`.* FROM `accounts` WHERE `accounts`.`id` = 20 LIMIT 1
↳ app/controllers/application_controller.rb:30:in `load_user'
CACHE Account Load (0.0ms) SELECT `accounts`.* FROM `accounts` WHERE `accounts`.`id` = 20 LIMIT 1 [["id", 20], ["LIMIT", 1]]
↳ app/controllers/accounts_controller.rb:97:in `load_account'
(0.1ms) BEGIN
↳ app/models/account.rb:148:in `assign_plan'
Plan Load (0.1ms) SELECT `plans`.* FROM `plans` WHERE `plans`.`id` = 1 LIMIT 1
↳ app/models/account.rb:148:in `assign_plan'
Account Update (0.2ms) UPDATE `accounts` SET `accounts`.`card_last_4` = NULL, `accounts`.`card_type` = NULL, `accounts`.`card_exp_month` = NULL, `accounts`.`card_exp_year` = NULL, `accounts`.`plan_id` = 1, `accounts`.`updated_at` = '2020-08-18 00:24:47' WHERE `accounts`.`id` = 20
↳ app/controllers/accounts_controller.rb:82:in `destroy_card'
Account Update (0.3ms) UPDATE `accounts` SET `accounts`.`plan_updated_at` = '2020-08-18 00:24:47' WHERE `accounts`.`id` = 20
↳ app/models/account.rb:60:in `stripe_subscribe'
(9.1ms) ROLLBACK
↳ app/controllers/accounts_controller.rb:82:in `destroy_card'
Completed 500 Internal Server Error in 1150ms (ActiveRecord: 10.4ms | Allocations: 22601)
NoMethodError (undefined method `[]' for nil:NilClass):
app/models/account.rb:71:in `stripe_subscribe'
app/controllers/accounts_controller.rb:82:in `destroy_card'
Code from account.rb
def stripe_subscribe
s = stripe_customer.subscriptions.first
self.plan_updated_at = Time.now
save!
if coupon.present? && plan.id != coupon.plan_id
self.coupon = nil
save!
end
if plan.price == 0
# Downgrading from a paid tier
if s.present?
meta = s.delete
self.changed_plan = Plan.find(previous_changes[:plan_id][0])
self.changed_plan_date = Time.at(meta['current_period_end']).to_datetime
save!
end
else
s.delete({ prorate: true, invoice_now: true }) if s.present?
params = { items: [{ plan: plan.short_name }] }
if coupon.present?
params[:coupon] = coupon.token
end
stripe_customer.subscriptions.create(params)
if Rails.env == 'production'
client = Slack::Web::Client.new
client.chat_postMessage(channel: '#somechannel', text: "some random message", as_user: true)
end
end
end

Different result in rails console and in puts

When I use puts(#participantt = Participant.where(id: 1)) then in the console I get
Participant Load (0.3ms) SELECT "participants".* FROM "participants" WHERE "participants"."id" = $1 [["id", 1]]
↳ app/controllers/interviews_controller.rb:119:in `puts'
#<Participant:0x000000000c778bf0>
But if I type #participantt = Participant.where(id: 1) in rails console then I get
Participant Load (0.7ms) SELECT "participants".* FROM "participants" WHERE "participants"."id" = $1 LIMIT $2 [["id", 1], ["LIMIT", 11]]
=> #<ActiveRecord::Relation [#<Participant id: 1, name: "Ram", email: "Ram#g.com", created_at: "2020-05-08 08:19:00", updated_at: "2020-05-08 08:19:00">]>
Why is this so?
puts calls to_s on before printing result of expression(which will be an object) passed to it. It generally prints class name with it's object id.
Here, result of #participant = Participant.where(id: 1) is the Participant with id and get stored in instance variable #participant
Passing #participant to puts will first call #participant.to_s before printing it.
In case of just #participant = Participant.where(id: 1), the console shows the result which is typical REPL utility does. And if you do puts #participant there after then you will again get same as what you get with puts in you question.

Rails: delete_all raises PG::NotNullViolation

I am importing a CSV with a few hundred rows into my rails database.
Occasionally the user wants to force overwrite the data so I figured that it would be best to destroy all the data and start fresh.
something like:
account.catalog_listings.delete_all if should_refresh
CSV.foreach(file, options) do |row|
account.catalog_listings.create!({...rowstuff})
problem is that delete_all line is raising the PG error
ActiveRecord::StatementInvalid (PG::NotNullViolation: ERROR: null value in column "account_id" violates not-null constraint
DETAIL: Failing row contains (1, null, ... ... ).
: UPDATE "catalog_listings" SET "account_id" = NULL WHERE "catalog_listings"."account_id" = $1):
app/models/catalog_listing.rb:41:in `import_catalog_listings'
app/controllers/accounts_controller.rb:20:in `catalog'
I DO have a null: false on a couple foreign key fields but i cannot figure out why delete_all is trying to remove the foreign key instead of removing the whole record?
UPDATE - everything works when I change:
account.catalog_listings.delete_all if should_refresh
to:
account.catalog_listings.destroy_all if should_refresh
except that destroy goes through each item and deletes one-by-one:
SQL (0.1ms) DELETE FROM "catalog_listings" WHERE "catalog_listings"."id" = $1 [["id", 957]]
SQL (0.1ms) DELETE FROM "catalog_listings" WHERE "catalog_listings"."id" = $1 [["id", 958]]
SQL (0.1ms) DELETE FROM "catalog_listings" WHERE "catalog_listings"."id" = $1 [["id", 959]]
SQL (0.1ms) DELETE FROM "catalog_listings" WHERE "catalog_listings"."id" = $1 [["id", 960]]
SQL (0.1ms) DELETE FROM "catalog_listings" WHERE "catalog_listings"."id" = $1 [["id", 961]]
SQL (0.1ms) DELETE FROM "catalog_listings" WHERE "catalog_listings"."id" = $1 [["id", 962]]
SQL (0.2ms) DELETE FROM "catalog_listings" WHERE "catalog_listings"."id" = $1 [["id", 963]]
SQL (0.2ms) DELETE FROM "catalog_listings" WHERE "catalog_listings"."id" = $1 [["id", 964]]
SQL (0.2ms) DELETE FROM "catalog_listings" WHERE "catalog_listings"."id" = $1 [["id", 965]]
SQL (0.2ms) DELETE FROM "catalog_listings" WHERE "catalog_listings"."id" = $1 [["id", 966]]
SQL (0.3ms) DELETE FROM "catalog_listings" WHERE "catalog_listings"."id" = $1 [["id", 967]]
SQL (0.2ms) DELETE FROM "catalog_listings" WHERE "catalog_listings"."id" = $1 [["id", 968]]
SQL (0.2ms) DELETE FROM "catalog_listings" WHERE "catalog_listings"."id" = $1 [["id", 969]]
SQL (0.2ms) DELETE FROM "catalog_listings" WHERE "catalog_listings"."id" = $1 [["id", 970]]
SQL (0.2ms) DELETE FROM "catalog_listings" WHERE "catalog_listings"."id" = $1 [["id", 971]]
SQL (0.2ms) DELETE FROM "catalog_listings" WHERE "catalog_listings"."id" = $1 [["id", 972]]
SQL (0.2ms) DELETE FROM "catalog_listings" WHERE "catalog_listings"."id" = $1 [["id", 973]]
SQL (0.3ms) DELETE FROM "catalog_listings" WHERE "catalog_listings"."id" = $1 [["id", 974]]
SQL (0.2ms) DELETE FROM "catalog_listings" WHERE "catalog_listings"."id" = $1 [["id", 975]]
not cool... anyone know a better way to do this?
Try adding dependent: :destroy in the catalog_listings association on your Account model.
https://apidock.com/rails/ActiveRecord/Associations/CollectionProxy/delete_all

Spree currency convertor is not working for AED

I have included following gem in my gem file
gem 'spree_multi_currency', github: 'spree/spree_multi_currency', branch: '2-3-stable'
in my application following currencies are already present:
SGD,USD,EUR,AUD,GBP,PHP,THB,MYR
and these are converting price properly. But my requirement is to add AED currency to so I have added that also SGD,USD,EUR,AUD,GBP,PHP,THB,MYR,AED from backend
Now I automatically got this option in my header now when i click on AED it gives me following error
Started GET "/assets/world-globe.png" for 127.0.0.1 at 2016-01-26 10:26:08 +0100
Started POST "/currency/set" for 127.0.0.1 at 2016-01-26 10:26:11
+0100 Processing by Spree::CurrencyController#set as JSON Parameters: {"currency"=>"AED"} Spree::Country Load (1.1ms) SELECT "spree_countries".* FROM "spree_countries" WHERE "spree_countries"."name" = 'N/A' LIMIT 1 Spree::User Load (1.2ms) SELECT "spree_users".* FROM "spree_users" WHERE "spree_users"."id" = 1 ORDER BY "spree_users"."id" ASC LIMIT 1 Spree::Order Load (1.2ms) SELECT "spree_orders".* FROM "spree_orders" WHERE "spree_orders"."completed_at" IS NULL AND "spree_orders"."currency" = 'USD' AND "spree_orders"."guest_token" = 'ZtR5IUlQUC40ueZBlo21Pg' AND "spree_orders"."user_id" = 1 LIMIT 1 Spree::Adjustment Load (1.4ms) SELECT "spree_adjustments".* FROM "spree_adjustments" WHERE "spree_adjustments"."adjustable_type" = 'Spree::Order' AND "spree_adjustments"."adjustable_id" IN (6084) ORDER BY spree_adjustments.created_at ASC Spree::Order Load (0.9ms) SELECT "spree_orders".* FROM "spree_orders" WHERE "spree_orders"."user_id" = $1 AND "spree_orders"."completed_at" IS NULL AND (id != 6084) [["user_id", 1]] (0.9ms) BEGIN Spree::Order Exists (1.7ms) SELECT 1 AS one FROM "spree_orders" WHERE ("spree_orders"."number" = 'R501407003' AND "spree_orders"."id" != 6084) LIMIT 1 Spree::LineItem Load (1.3ms) SELECT "spree_line_items".* FROM "spree_line_items" WHERE "spree_line_items"."order_id" = $1 AND (currency != 'AED') ORDER BY created_at ASC [["order_id", 6084]] Spree::Variant Load (1.3ms) SELECT "spree_variants".* FROM "spree_variants" WHERE "spree_variants"."id" = $1 LIMIT 1 [["id", 2]] Spree::Price Load (1.3ms) SELECT "spree_prices".* FROM "spree_prices" WHERE "spree_prices"."deleted_at" IS NULL AND "spree_prices"."variant_id" = $1 AND "spree_prices"."currency" = 'AED' ORDER BY "spree_prices"."id" ASC LIMIT 1 [["variant_id", 2]] Spree::Product Load (1.3ms) SELECT "spree_products".* FROM "spree_products" WHERE "spree_products"."id" = $1 LIMIT 1 [["id", 2]] Spree::Product::Translation Load (1.3ms) SELECT "spree_product_translations".* FROM "spree_product_translations" WHERE "spree_product_translations"."spree_product_id" = $1 [["spree_product_id", 2]] (1.5ms) ROLLBACK Completed 500 Internal Server Error in 56ms
RuntimeError - no AED price found for 28 Day Ultimate Teatox (28 Day): () Users/TopFormInvestment/.rvm/gems/ruby-2.1.4#skinnymint/bundler/gems/spree-cfe7e96539b6/core/app/models/spree/order/currency_updater.rb:34:in `update_line_item_price!' () Users/TopFormInvestment/.rvm/gems/ruby-2.1.4#skinnymint/bundler/gems/spree-cfe7e96539b6/core/app/models/spree/order/currency_updater.rb:18:in `block in update_line_item_currencies!'
Please guide me how to solve this error. As I am new in spree
Go to the Products in admin panel. There you can see the price tab, click the tab and then you change the prices there itself.
You did not set an AED price for the variant 28 Day Ultimate Teatox. In update_line_items_price! it has a local variable price which returns the variants price in the newly set currency. If the price isn't present it will raise the RuntimeError you are getting.
def update_line_item_currencies!
line_items.where('currency != ?', currency).each do |line_item|
update_line_item_price!(line_item)
end
end
# Returns the price object from given item
def price_from_line_item(line_item)
line_item.variant.prices.where(currency: currency).first
end
# Updates price from given line item
def update_line_item_price!(line_item)
price = price_from_line_item(line_item)
if price
line_item.update_attributes!(currency: price.currency, price: price.amount)
else
raise RuntimeError, "no #{currency} price found for #{line_item.product.name} (#{line_item.variant.sku})"
end
end

Rails infinite loop while updating other record's value during `before_save`

I have this model in Rails (trimmed to the relevant parts)
class Session < ActiveRecord::Base
belongs_to :user
before_save :invalidate_existing_sessions
def invalidate_existing_sessions
Session.where(user_id: user.id, current: true).each { |sess| sess.update_attributes(current: false) }
end
end
However, when a record is created and about to be saved, the server goes into an infinite loop.
Here are the server logs
Processing by V1::SessionsController#create as */*
Parameters: {"email"=>"user#example.com", "password"=>"[FILTERED]", "session"=>{}}
User Load (0.7ms) SELECT "users".* FROM "users" WHERE "users"."email" = $1 LIMIT 1 [["email", "user#example.com"]]
(0.2ms) BEGIN
Session Load (0.7ms) SELECT "sessions".* FROM "sessions" WHERE "sessions"."user_id" = $1 AND "sessions"."current" = $2 [["user_id", 1
], ["current", true]]
User Load (0.3ms) SELECT "users".* FROM "users" WHERE "users"."id" = $1 LIMIT 1 [["id", 1]]
CACHE (0.0ms) SELECT "sessions".* FROM "sessions" WHERE "sessions"."user_id" = $1 AND "sessions"."current" = $2 [["user_id", 1], ["cu
rrent", true]]
CACHE (0.0ms) SELECT "users".* FROM "users" WHERE "users"."id" = $1 LIMIT 1 [["id", 1]]
CACHE (0.0ms) SELECT "sessions".* FROM "sessions" WHERE "sessions"."user_id" = $1 AND "sessions"."current" = $2 [["user_id", 1], ["cu
rrent", true]]
CACHE (0.0ms) SELECT "users".* FROM "users" WHERE "users"."id" = $1 LIMIT 1 [["id", 1]]
CACHE (0.0ms) SELECT "sessions".* FROM "sessions" WHERE "sessions"."user_id" = $1 AND "sessions"."current" = $2 [["user_id", 1], ["cu
rrent", true]]
A bit later, this is what the log turns into
app/models/session.rb:12:in `invalidate_existing_sessions'
app/models/session.rb:12:in `block in invalidate_existing_sessions'
app/models/session.rb:12:in `invalidate_existing_sessions'
app/models/session.rb:12:in `block in invalidate_existing_sessions'
app/models/session.rb:12:in `invalidate_existing_sessions'
app/models/session.rb:12:in `block in invalidate_existing_sessions'
app/models/session.rb:12:in `invalidate_existing_sessions'
Any ideas? I'm using Rails 5 alpha.
It's because your before_save method does this...
sess.update_attributes(current: false)
Since update_attributes calls before_save you are (as you say) in an infinite loop.
So you need to skip the callbacks
class Session < ActiveRecord::Base
attr_accessor :skip_callbacks
before_save :invalidate_existing_sessions, unless: :skip_callbacks
def invalidate_existing_sessions
Session.where(user_id: user.id, current: true).each do |sess|
sess.skip_callbacks = true
sess.update_attributes(current: false)
end
end
Even though all of the above answers worked for me, this is what I found simplest and I ended up using.
def invalidate_existing_sessions
Session.where(user_id: user.id, current: true).each { |sess| sess.update_column(:current, false) }
end
Turns out update_column doesn't call any callbacks, but as an disadvantage it doesn't update updated_at if you're using timestamps in your model.
You're running update_attributes in before_save, that means you're saving before save. That's why it goes into an infinite loop.

Resources