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

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

Related

rails test not allowing to assert processing of before_action

The following unit test succeeds in the first assertion, but fails in the second
test "login_name, kee and virtual_qr changed" do
#user = users(:funky_mobile)
assert_changes 'users(:funky_mobile).mobile' do
#user.update(address: 'muuvt', mobile: '728363', mobile_nation_id: 1)
# patch update_user_path(#user_mobile), params: { user: { address: 'muuvt', mobile: '728364', mobile_nation_id: 1 } }
end
assert_changes 'users(:funky_mobile).login_name' do
#user.update(address: 'muuvt', mobile: '728365', mobile_nation_id: 1)
end
end
"users(:funky_mobile).login_name" didn't change.
Note: while patch - attempted as per the following - does process correctly, it appears not applicable to a unit test.
The unit test with update only registers the submitted params but does not kick in the before_action, as per test.log
User Update (0.5ms)[0m [1m[33mUPDATE "users" SET "mobile" = $1 WHERE "users"."id" = $2[0m [["mobile", 728365], ["id", 165956397]]
Conversely, with an integration test
sign_in users(:funky_mobile)
assert_changes 'users(:funky_mobile).login_name' do
patch user_url(#user_mobile), params: { user: { address: 'muuvt', mobile: '728364', mobile_nation_id: 1 } }
end
"users(:funky_mobile).login_name" didn't change.
Expected nil to not be equal to nil.
the changed data enacted via before_action :set_user_login_name, only: %i[ update ] of the users_controller
def set_user_login_name
if params[:user][:email].present?
params[:user][:login_name] = params[:user][:email].gsub(/\s+/, "")
elsif params[:user][:mobile_nation_id].present? && params[:user][:mobile].present?
#nation = Nation.where(id: params[:user][:mobile_nation_id]).first
params[:user][:login_name] = #nation.phone_cc.to_s + params[:user][:mobile].to_s
params[:user][:twilio_number] = '+' + #nation.phone_cc.to_s + params[:user][:mobile].to_s
else
params[:user][:login_name]
end
params[:user][:kee] = SecureRandom.alphanumeric(32)
params[:user][:virtual_qr_code] = params[:user][:login_name] + params[:user][:kee]
end
is processed as demonstrated by the test.log
User Update (0.7ms)[0m [1m[33mUPDATE "users" SET "login_name" = $1, "kee" = $2, "virtual_qr_code" = $3 WHERE "users"."id" = $4[0m [["login_name", "39728364"], ["kee", "Rce8sQoH0VPvqUPeuegZL4gYVmJuamqi"], ["virtual_qr_code", "39728364Rce8sQoH0VPvqUPeuegZL4gYVmJuamqi"], ["id", 165956397]]
TRANSACTION (0.1ms)[0m [1m[35mRELEASE SAVEPOINT active_record_1[0m
Redirected to http://www.example.com/users/165956397
Oddly, if the integration test is altered reomving assert_changes to simply
patch user_url(#user_mobile), params: { user: { address: 'muuvt', mobile: '728364', mobile_nation_id: 1 } }
puts #user_mobile.mobile
assert_equal(39728364, #user_mobile.mobile)
returns
3331112200
F [...]
Expected: 39728364
Actual: 3331112200
yet the log shows the same User update reference as above.
How can I properly assert that these changes are being carried forth?
This is going to fail...
assert_changes 'users(:funky_mobile).login_name' do
because...
users(:funky_mobile).login_name
returns the original value every time. It is calling the fixture and acts like a constant.
What you should do is...
login_name = users(:funky_mobile).login_name
assert_changes login_name do

How to avoid destroy deleting earlier related object

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

usage of query where in controller

I want to display events of specific season and championship, but I have all the events of a championship. Where I am not right?
resources :championships do
resources :seasons do
resources :events
end
end
class EventsController < ApplicationController
def index
#events = #championship.events.where(params[:season_id] == #season.id)
end
end
Started GET "/championships/2/seasons/2/events" for 127.0.0.1 at 2016-12-28 12:07:07 +0200
Processing by EventsController#index as HTML
Parameters: {"championship_id"=>"2", "season_id"=>"2"}
Championship Load (0.3ms) SELECT "championships".* FROM "championships" WHERE "championships"."id" = $1 LIMIT 1 [["id", 2]]
Season Load (0.3ms) SELECT "seasons".* FROM "seasons" WHERE "seasons"."id" = $1 LIMIT 1 [["id", 2]]
Here is your error:
#events = #championship.events.where(params[:season_id] == #season.id)
You give where either true or false
but you need to do this:
#events = #championship.events.where(:season_id => params[:season_id])

Rails update_Attributes(params[:user])

I have a User show function that makes an api call and updates the user attributes, but I'm having trouble saving the changes.
def show
#user = User.find(params[:id])
... change attributes of #user ...
if #user.update_attributes(params[:user])
p "Saved"
else
p "Failed"
end
end
I'm updated two attributes (:today_steps and :year). Both are accessible in the user.rb. The challenge is that :year is a Serialized Array, but I'm not sure how that changes anything
this setup has returned a 'Failed' every time. i have also tried 'params[:id]' but I receive the error
undefined method `stringify_keys' for "1":String
Any ideas on how to solve this? thanks
more info
def show
#user = User.find(params[:id])
if (#user.device != nil)
#device = #user.device
client = Fitgem::Client.new(
#api client - haven't figured out my security yet, so I won't post it
)
now = Time.now()
last = #device.lastUpdated
while now.to_date > last.to_date
day = client.activities_on_date last.strftime("%Y-%m-%d")
break if day['errors'] != nil
day = day['summary']['steps']
last = last + 1.days
#user.year = #user.year.unshift(day)
end
day = (client.activities_on_date 'today')
if day['errors'] == nil
#user.today_steps = day['summary']['steps']
if now.day != last.day
#user.year.unshift(#user.today_steps)
else
#user.year[0] = #user.today_steps
end
end
#device.lastUpdated = now
p #user.year
#user.device.save
if #user.update_attributes(params[:user])
p "Updated"
else
p "Failed to Update"
end
end
#competitions = #user.competitions.paginate(page: params[:page])
end
_
User.rb
attr_accessible :email, :name, :password, :password_confirmation, :year, :today_steps
serialize :year, Array
Even More
console, using params[:user]
Started GET "/users/2" for 127.0.0.1 at 2014-02-25 17:15:09 -0800
Processing by UsersController#show as HTML
Parameters: {"id"=>"2"}
User Load (0.1ms) SELECT "users".* FROM "users" WHERE "users"."id" = ? LIMIT 1 [["id", "2"]]
Device Load (0.1ms) SELECT "devices".* FROM "devices" WHERE "devices"."user_id" = 2 LIMIT 1
(0.1ms) begin transaction
(0.3ms) UPDATE "devices" SET "lastUpdated" = '2014-02-26 01:15:09.634622', "updated_at" = '2014-02-26 01:15:10.392810' WHERE "devices"."id" = 3
(2.3ms) commit transaction
(0.1ms) begin transaction
User Exists (0.1ms) SELECT 1 FROM "users" WHERE (LOWER("users"."email") = LOWER('fire#fox.com') AND "users"."id" != 2) LIMIT 1
(0.0ms) rollback transaction
Rendered users/show.html.erb within layouts/application (0.4ms)
Rendered layouts/_shim.html.erb (0.0ms)
User Load (0.1ms) SELECT "users".* FROM "users" WHERE "users"."remember_token" = '1f47eae1cb002cb1c4e83ce0363fbfb2d33ad8f5' LIMIT 1
Rendered layouts/_header.html.erb (2.2ms)
Rendered layouts/_footer.html.erb (0.1ms)
console #user after find
#<User id: 1, name: "Marcus", email: "mar#comcast.net", points: nil, created_at: "2014-02-25 21:59:12", updated_at: "2014-02-25 21:59:12", password_digest: "$2aGTx..FbLP...", admin: false, remember_token: "e4bdd9c", year: [], lastUpdate: nil, lastUpdated: nil, today_steps: nil>
Your code is as
#user = User.find(params[:id])
... change attributes of #user ...
if #user.update_attributes(params[:user])
#the log
Started GET "/users/2" for 127.0.0.1 at 2014-02-25 17:15:09 -0800
Processing by UsersController#show as HTML
Parameters: {"id"=>"2"}
the log clearly states that the show method receives only 'id' whereas in your controller your expect a hash 'user' which can be supplied to update_attributes.
'show' expects to get an attributes hash to stringify it's keys for the column names.

rails custom validation not failing when it should

This might not be the cleanest code yet, still quite new to Ruby...
I have the following spam check method in my message.rb model:
validate :no_spam?, :if => "sender_user_id != nil"
private
def no_spam?
#first easy spam detection, if the (hidden by css) company field is filled, it is spam for sure
if !company.blank?
errors.add(:body, I18n.t(:No_spam_allowed))
return false
end
#Mollom advanced spam detection
m = Mollom.new(:private_key => 'xxx',
:public_key => 'xxx')
#check content in case it is a first submit of the form
if captcha_session_id.blank?
content = m.check_content(:post_body => body,
:author_name => sender_name,
:author_mail => sender_email,
:author_ip => sender_ip)
else
#check captcha if the form was resumbitted after an unsure result
logger.debug "DEBUG: GOING TO CHECK CAPTCHA"
result = m.valid_captcha?(:session_id => captcha_session_id,
:solution => captcha_solution.chomp)
if result
logger.debug "DEBUG: TRUE -> GOOD CAPTCHA"
return true
else
logger.debug "DEBUG: FALSE -> BAD CAPTCHA"
return false
end
end
#returning the right values and error messages for different content check outcomes
logger.debug "DEBUG: I'M CONTINUING THE METHOD EXECUTION"
if content.spam?
logger.debug "DEBUG: SPAM DETECTED"
errors.add(:body, I18n.t(:No_spam_allowed))
return false
elsif content.unsure?
logger.debug "DEBUG: MESSAGE UNSURE - FAIL FORM BUT SHOW CAPTCHA"
errors.add(:captcha_solution, I18n.t(:Type_the_characters_you_see_in_the_picture_below))
self.captcha_image_url = m.image_captcha(:session_id => content.session_id)["url"]
self.captcha_session_id = content.session_id
return false
else
logger.debug "DEBUG: MESSAGE OK!"
return true
end
end
development.log
Processing MessagesController#create (for 127.0.0.1 at 2011-08-12 12:01:24) [POST]
Parameters: {"commit"=>"Verzend", "action"=>"create", "authenticity_token"=>"xxxxxxxxxxx", "locale"=>"nl", "controller"=>"messages", "message"=>{"sender_email"=>"[FILTERED]", "company"=>"", "body"=>"unsure", "sender_phone"=>"xxxx", "sender_name"=>"Admin ImmoNatie"}}
Message Columns (6.0ms) SHOW FIELDS FROM `messages`
User Columns (10.0ms) SHOW FIELDS FROM `users`
User Load (7.0ms) SELECT * FROM `users` WHERE (`users`.`id` = '1') AND (users.deleted_at IS NULL ) LIMIT 1
SQL (0.0ms) BEGIN
User Update (0.0ms) UPDATE `users` SET `updated_at` = '2011-08-12 10:01:25', `perishable_token` = 'xxxxxxxxxxx', `last_request_at` = '2011-08-12 10:01:25' WHERE `id` = 1
SQL (3.0ms) COMMIT
SQL (0.0ms) BEGIN
DEBUG: I'M CONTINUING THE METHOD EXECUTION
DEBUG: MESSAGE UNSURE - FAIL FORM BUT SHOW CAPTCHA
SQL (0.0ms) ROLLBACK
Rendering template within layouts/application
Rendering messages/new
Rendered messages/_form (8.0ms)
Rendered layouts/_google_analytics (0.0ms)
Rendered layouts/_login (3.0ms)
Rendered layouts/_navigation (6.0ms)
Rendered layouts/_header (12.0ms)
Rendered about_us/_ten_reasons_9_body (0.0ms)
NewsletterEmail Columns (5.0ms) SHOW FIELDS FROM `newsletter_emails`
Rendered layouts/_footer (41.0ms)
Completed in 1907ms (View: 70, DB: 40) | 200 OK [http://infinitize.dynalias.com/contact]
tize.dynalias.com/contact]
SQL (0.0ms) SET SQL_AUTO_IS_NULL=0
Property Columns (10.0ms) SHOW FIELDS FROM `properties`
Processing MessagesController#create (for 127.0.0.1 at 2011-08-12 12:01:32) [POST]
Parameters: {"commit"=>"Verzend", "action"=>"create", "authenticity_token"=>"xxxxxxxxxxx", "locale"=>"nl", "controller"=>"messages", "message"=>{"sender_email"=>"[FILTERED]", "company"=>"", "body"=>"unsure", "captcha_solution"=>"", "sender_phone"=>"xx", "captcha_session_id"=>"xxxxxxxxxxx", "sender_name"=>"Admin ImmoNatie"}}
Message Columns (5.0ms) SHOW FIELDS FROM `messages`
User Columns (10.0ms) SHOW FIELDS FROM `users`
User Load (0.0ms) SELECT * FROM `users` WHERE (`users`.`id` = '1') AND (users.deleted_at IS NULL ) LIMIT 1
SQL (0.0ms) BEGIN
User Update (0.0ms) UPDATE `users` SET `updated_at` = '2011-08-12 10:01:32', `perishable_token` = 'xxxxxxxxxxx', `last_request_at` = '2011-08-12 10:01:32' WHERE `id` = 1
SQL (4.0ms) COMMIT
SQL (0.0ms) BEGIN
DEBUG: GOING TO CHECK CAPTCHA
DEBUG: FALSE -> BAD CAPTCHA
Message Create (0.0ms) INSERT INTO `messages` (`sender_email`, `receiver_user_id`, `receiver_email`, `created_at`, `body`, `opened_by_owner`, `updated_at`, `receiver_name`, `opened_by_sender`, `sender_ip`, `message_thread_id`, `sender_user_id`, `sender_name`) VALUES('admin#immonatie.be', 1, 'test#immonatie.be', '2011-08-12 10:01:33', 'unsure', NULL, '2011-08-12 10:01:33', 'ImmoNatie', NULL, '127.0.0.1', NULL, 1, 'Admin ImmoNatie')
MessageThread Columns (5.0ms) SHOW FIELDS FROM `message_threads`
MessageThread Create (1.0ms) INSERT INTO `message_threads` (`last_message_opened_by_sender_id`, `answered`, `initial_sender_user_id`, `created_at`, `initial_sender_email`, `starred`, `updated_at`, `last_message_opened_by_owner_id`, `type_id`, `owner_id`, `property_id`, `first_message_id`, `initial_sender_name`, `initial_sender_phone`, `last_message_id`, `last_message_added_at`) VALUES(213, NULL, 1, '2011-08-12 10:01:33', 'admin#immonatie.be', 0, '2011-08-12 10:01:33', 0, 174, 1, NULL, 213, 'Admin ImmoNatie', 'xx', 213, '2011-08-12 10:01:33')
Message Update (0.0ms) UPDATE `messages` SET `updated_at` = '2011-08-12 10:01:33', `message_thread_id` = 101, `sender_name` = 'Admin ImmoNatie', `created_at` = '2011-08-12 10:01:33', `sender_email` = 'admin#immonatie.be', `sender_ip` = '127.0.0.1', `sender_user_id` = 1, `receiver_name` = 'ImmoNatie', `receiver_email` = 'test#immonatie.be', `body` = 'unsure', `receiver_user_id` = 1 WHERE `id` = 213
Sent mail to test#immonatie.be
Date: Fri, 12 Aug 2011 12:01:33 +0200
From: Notifications <no-reply#immonatie.be>
To: test#immonatie.be
Subject: Nieuw contact bericht
Mime-Version: 1.0
Content-Type: text/html; charset=utf-8
Naam: xxxx<br />
E-mail: xxxx<br />
Telefoon: xxxx<br />
<br />
Bericht:<br />
unsure
SQL (3.0ms) COMMIT
In the development.log you see that I first submit the form (first create action) with 'unsure' in the body to invoke an unsure result from Mollom (this site is in development mode).
The validation fails for this first create action as expected.
But when I resubmit the form now with an empty captcha verification code, the validation method returns false, but the validation does not, since the save is continued and COMMITTED in the end.
Why does this validation not fail and break (rollback) the create action?
Thanks,
Michael
Found the problem. Returning false to the validation was not enough. I needed to add an error: errors.add(:body, "error message"). This error together with return false did the job.

Resources