Related
So I have this resource (User) that I am trying to test the updating of. I am using Ruby 3.0.1, Rails 6.1.4, Devise 4.8.1, and Recaptcha 5.8.1. Here's the User:
class User < ApplicationRecord
# Include default devise modules. Others available are:
# :confirmable, :lockable, :timeoutable, :trackable and :omniauthable
devise :database_authenticatable, :registerable, :trackable,
:recoverable, :rememberable, :validatable, :confirmable
include Elasticsearch::Model
scope :visible_to_public, -> { where(searchable: true) }
scope :activated, -> { where('users.confirmed_at IS NOT NULL') }
index_name "users-#{Rails.env}"
has_one_attached :avatar
has_many :widgets, dependent: :destroy
has_many :active_relationships, class_name: "Relationship",
foreign_key: "follower_id",
dependent: :destroy
has_many :passive_relationships, class_name: "Relationship",
foreign_key: "followed_id",
dependent: :destroy
has_many :following, through: :active_relationships, source: :followed
has_many :followers, through: :passive_relationships, source: :follower
has_many :reports, dependent: :destroy
has_many :comments, dependent: :destroy
validates :name, presence: true, length: { maximum: 50 }
VALID_EMAIL_REGEX = /\A[\w+\-.]+#[a-z\d\-.]+\.[a-z]+\z/i
validates :email, presence: true, length: { maximum: 255 },
format: { with: VALID_EMAIL_REGEX },
uniqueness: true
Here's the test:
test "successful edit" do
sign_in #user, scope: :user
name = "Foo Bar"
handle = "MrFoo"
put user_registration_path, params: { user: { name: name,
username: handle,
email: #user.email,
password: '',
password_confirmation:'',
current_password: #user.current_password }}
assert_response :success
puts "User Errors: #{#user.errors.full_messages}\n"
#user.reload
puts "User: #{#user.inspect}\n"
assert_equal name, #user.name
assert_equal handle, #user.username
end
The assert_equal name is failing and the User errors from the put statement in the test is an empty array '[]'.
I created a Devise Registration controller so I could use the recaptcha gem. It has very little code. Here it is:
class Users::RegistrationsController < Devise::RegistrationsController
before_action :configure_sign_up_params, only: [:create]
before_action :configure_account_update_params, only: [:update]
def update
if verify_recaptcha
super
else
self.resource = resource_class.new sign_up_params
flash.now[:error] = "Recaptcha cannot be blank; please try again"
redirect_to edit_user_registration_path
end
end
protected
# If you have extra params to permit, append them to the sanitizer.
def configure_sign_up_params
sign_up_attrs = [:password, :password_confirmation, :name, :username, :avatar]
devise_parameter_sanitizer.permit(:sign_up, keys: [sign_up_attrs])
end
# If you have extra params to permit, append them to the sanitizer.
def configure_account_update_params
update_attrs = [:password, :password_confirmation, :current_password, :name, :username, :avatar]
devise_parameter_sanitizer.permit(:account_update, keys: [update_attrs])
end
end
Here's the log:
-----------------------------------
UsersEditTest: test_successful_edit
-----------------------------------
[1m[36mUser Load (0.4ms)[0m [1m[34mSELECT "users".* FROM "users" WHERE "users"."id" = ? LIMIT ?[0m [["id", 688598839], ["LIMIT", 1]]
[1m[36mUser Load (0.1ms)[0m [1m[34mSELECT "users".* FROM "users" WHERE "users"."id" = ? LIMIT ?[0m [["id", 838564783], ["LIMIT", 1]]
Started PUT "/users" for 127.0.0.1 at 2022-01-25 17:32:25 -0500
[1m[36mTRANSACTION (0.1ms)[0m [1m[35mSAVEPOINT active_record_1[0m
[1m[36mUser Update (0.4ms)[0m [1m[33mUPDATE "users" SET "updated_at" = ?, "sign_in_count" = ?, "current_sign_in_at" = ?, "last_sign_in_at" = ?, "current_sign_in_ip" = ?, "last_sign_in_ip" = ? WHERE "users"."id" = ?[0m [["updated_at", "2022-01-25 22:32:25.237068"], ["sign_in_count", 1], ["current_sign_in_at", "2022-01-25 22:32:25.236226"], ["last_sign_in_at", "2022-01-25 22:32:25.236226"], ["current_sign_in_ip", "127.0.0.1"], ["last_sign_in_ip", "127.0.0.1"], ["id", 688598839]]
[1m[36mActiveStorage::Attachment Load (0.1ms)[0m [1m[34mSELECT "active_storage_attachments".* FROM "active_storage_attachments" WHERE "active_storage_attachments"."record_id" = ? AND "active_storage_attachments"."record_type" = ? AND "active_storage_attachments"."name" = ? LIMIT ?[0m [["record_id", 688598839], ["record_type", "User"], ["name", "avatar"], ["LIMIT", 1]]
[1m[36mUser Exists? (0.2ms)[0m [1m[34mSELECT 1 AS one FROM "users" WHERE "users"."email" = ? AND "users"."id" != ? LIMIT ?[0m [["email", "nick#example.com"], ["id", 688598839], ["LIMIT", 1]]
[1m[36mActiveStorage::Blob Load (0.2ms)[0m [1m[34mSELECT "active_storage_blobs".* FROM "active_storage_blobs" INNER JOIN "active_storage_attachments" ON "active_storage_blobs"."id" = "active_storage_attachments"."blob_id" WHERE "active_storage_attachments"."record_id" = ? AND "active_storage_attachments"."record_type" = ? AND "active_storage_attachments"."name" = ? LIMIT ?[0m [["record_id", 688598839], ["record_type", "User"], ["name", "avatar"], ["LIMIT", 1]]
[1m[36mActiveStorage::Blob Create (0.4ms)[0m [1m[32mINSERT INTO "active_storage_blobs" ("key", "filename", "content_type", "metadata", "byte_size", "checksum", "created_at", "service_name") VALUES (?, ?, ?, ?, ?, ?, ?, ?)[0m [["key", "c8w5ycv9gy4c67phehpbdvwxdigo"], ["filename", "default_avatar2.png"], ["content_type", "image/png"], ["metadata", "{\"identified\":true}"], ["byte_size", 15693], ["checksum", "4IDAjCeSqMrDM9F9s68Wtw=="], ["created_at", "2022-01-25 22:32:25.271303"], ["service_name", "test"]]
[1m[36mActiveStorage::Attachment Create (0.3ms)[0m [1m[32mINSERT INTO "active_storage_attachments" ("name", "record_type", "record_id", "blob_id", "created_at") VALUES (?, ?, ?, ?, ?)[0m [["name", "avatar"], ["record_type", "User"], ["record_id", 688598839], ["blob_id", 1], ["created_at", "2022-01-25 22:32:25.273083"]]
[1m[36mUser Update (0.1ms)[0m [1m[33mUPDATE "users" SET "updated_at" = ? WHERE "users"."id" = ?[0m [["updated_at", "2022-01-25 22:32:25.274730"], ["id", 688598839]]
[1m[36mTRANSACTION (0.1ms)[0m [1m[35mRELEASE SAVEPOINT active_record_1[0m
[36m Disk Storage (0.7ms) [0m[32mUploaded file to key: c8w5ycv9gy4c67phehpbdvwxdigo (checksum: 4IDAjCeSqMrDM9F9s68Wtw==)[0m
[ActiveJob] Enqueued ActiveStorage::AnalyzeJob (Job ID: c2fffb8c-2df4-4224-a96c-38e6185954b8) to Test(active_storage_analysis) with arguments: #<GlobalID:0x000055cf7cde5098 #uri=#<URI::GID gid://saverd/ActiveStorage::Blob/1>>
Processing by Users::RegistrationsController#update as HTML
Parameters: {"user"=>{"name"=>"Foo Bar", "username"=>"MrFoo", "email"=>"nick#example.com", "password"=>"[FILTERED]", "password_confirmation"=>"[FILTERED]", "current_password"=>"[FILTERED]"}}
[1m[36mUser Load (0.1ms)[0m [1m[34mSELECT "users".* FROM "users" WHERE "users"."id" = ? LIMIT ?[0m [["id", 688598839], ["LIMIT", 1]]
[1m[36mUser Exists? (0.1ms)[0m [1m[34mSELECT 1 AS one FROM "users" WHERE "users"."email" = ? AND "users"."id" != ? LIMIT ?[0m [["email", "nick#example.com"], ["id", 688598839], ["LIMIT", 1]]
Rendering layout layouts/application.html.erb
Rendering users/registrations/edit.html.erb within layouts/application
Rendered users/shared/_error_messages.html.erb (Duration: 1.5ms | Allocations: 949)
[1m[36mActiveStorage::Attachment Load (0.3ms)[0m [1m[34mSELECT "active_storage_attachments".* FROM "active_storage_attachments" WHERE "active_storage_attachments"."record_id" = ? AND "active_storage_attachments"."record_type" = ? AND "active_storage_attachments"."name" = ? LIMIT ?[0m [["record_id", 688598839], ["record_type", "User"], ["name", "avatar"], ["LIMIT", 1]]
[1m[36mActiveStorage::Blob Load (0.1ms)[0m [1m[34mSELECT "active_storage_blobs".* FROM "active_storage_blobs" WHERE "active_storage_blobs"."id" = ? LIMIT ?[0m [["id", 1], ["LIMIT", 1]]
Rendered users/registrations/edit.html.erb within layouts/application (Duration: 12.9ms | Allocations: 7556)
[Webpacker] Everything's up-to-date. Nothing to do
Rendered layouts/_shim.html.erb (Duration: 0.3ms | Allocations: 85)
Rendered layouts/_head.html.erb (Duration: 4.1ms | Allocations: 1988)
[36m Disk Storage (0.1ms) [0m[34mChecked if file exists at key: variants/c8w5ycv9gy4c67phehpbdvwxdigo/f0565870533d712d9f81cf6c91b03ed2afd53144cf67b4fdca912bf91444366f (no)[0m
[36m Disk Storage (0.1ms) [0m[34mDownloaded file from key: c8w5ycv9gy4c67phehpbdvwxdigo[0m
[36m Disk Storage (0.4ms) [0m[32mUploaded file to key: variants/c8w5ycv9gy4c67phehpbdvwxdigo/f0565870533d712d9f81cf6c91b03ed2afd53144cf67b4fdca912bf91444366f[0m
[1m[35m (0.2ms)[0m [1m[34mSELECT COUNT(*) FROM "widgets" WHERE "widgets"."user_id" = ?[0m [["user_id", 688598839]]
Rendered shared/_user_info.html.erb (Duration: 90.4ms | Allocations: 3974)
[1m[35m (0.2ms)[0m [1m[34mSELECT COUNT(*) FROM "users" INNER JOIN "relationships" ON "users"."id" = "relationships"."followed_id" WHERE "relationships"."follower_id" = ?[0m [["follower_id", 688598839]]
[1m[35m (0.2ms)[0m [1m[34mSELECT COUNT(*) FROM "users" INNER JOIN "relationships" ON "users"."id" = "relationships"."follower_id" WHERE "relationships"."followed_id" = ?[0m [["followed_id", 688598839]]
Rendered shared/_stats.html.erb (Duration: 10.6ms | Allocations: 2077)
Rendered shared/_user_widget_search.html.erb (Duration: 2.4ms | Allocations: 429)
[1m[35m (0.3ms)[0m [1m[34mSELECT COUNT(*) FROM "widgets" INNER JOIN "widget_references" ON "widgets"."id" = "widget_references"."referenced_id" WHERE "widget_references"."referencer_id" = ?[0m [["referencer_id", 688598839]]
[1m[35mCACHE (0.0ms)[0m [1m[34mSELECT COUNT(*) FROM "widgets" WHERE "widgets"."user_id" = ?[0m [["user_id", 688598839]]
Rendered shared/_widget_box.html.erb (Duration: 5.2ms | Allocations: 1066)
[1m[35m (0.2ms)[0m [1m[34mSELECT COUNT(*) FROM "categories"[0m
[1m[36mCategory Load (0.3ms)[0m [1m[34mSELECT "categories".* FROM "categories" ORDER BY "categories"."sequence" ASC[0m
Rendered shared/_categories.html.erb (Duration: 11.0ms | Allocations: 4993)
Rendered shared/_sidebar_user.html.erb (Duration: 133.4ms | Allocations: 13724)
Rendered layouts/_header.html.erb (Duration: 136.2ms | Allocations: 14611)
Rendered shared/_alerts.html.erb (Duration: 0.7ms | Allocations: 185)
Rendered layouts/_footer.html.erb (Duration: 1.0ms | Allocations: 310)
Rendered layout layouts/application.html.erb (Duration: 158.3ms | Allocations: 25688)
Completed 200 OK in 172ms (Views: 159.2ms | ActiveRecord: 2.1ms | Allocations: 33566)
[1m[36mUser Load (0.1ms)[0m [1m[34mSELECT "users".* FROM "users" WHERE "users"."id" = ? LIMIT ?[0m [["id", 688598839], ["LIMIT", 1]]
[1m[36mTRANSACTION (0.4ms)[0m [1m[31mrollback transaction[0m
When I run the server and do this manually it works. I also have turbo disabled on all of my forms. I'm stumped.
Despite providing the name, the SQL query clearly shows that it's not being passed properly. Rails console doesn't require any whitelist parameters as far as I'm aware, but I've included my controller as well.
Query in rails console: Profession.first.skills.create(name: 'rails')
Profession Load (0.5ms) SELECT "professions".* FROM "professions" ORDER BY "professions"."id" ASC LIMIT $1 [["LIMIT", 1]]
(0.2ms) BEGIN
Skill Exists (0.4ms) SELECT 1 AS one FROM "skills" WHERE "skills"."name" = $1 LIMIT $2 [["name", "twitter"], ["LIMIT", 1]]
SQL (1.0ms) INSERT INTO "skills" ("profession_id", "created_at", "updated_at") VALUES ($1, $2, $3) RETURNING "id" [["profession_id", 1], ["created_at", "2017-12-18 12:22:11.154775"], ["updated_at", "2017-12-18 12:22:11.154775"]]
(0.1ms) ROLLBACK
Not sure what's going on here.
Validation errors are still working though...
Valid object:
:027 > Skill.new(name: "rails", profession: Profession.first).valid?
Profession Load (0.4ms) SELECT "professions".* FROM "professions" ORDER BY "professions"."id" ASC LIMIT $1 [["LIMIT", 1]]
Skill Exists (1.9ms) SELECT 1 AS one FROM "skills" WHERE "skills"."name" = $1 LIMIT $2 [["name", "twitter"], ["LIMIT", 1]]
=> true
Name being detected for validations:
:020 > Skill.create!(name: String.new, profession: Profession.first)
Profession Load (0.4ms) SELECT "professions".* FROM "professions" ORDER BY "professions"."id" ASC LIMIT $1 [["LIMIT", 1]]
(0.1ms) BEGIN
Skill Exists (0.4ms) SELECT 1 AS one FROM "skills" WHERE "skills"."name" = $1 LIMIT $2 [["name", ""], ["LIMIT", 1]]
(0.1ms) ROLLBACK
ActiveRecord::RecordInvalid: Validation failed: Name can't be blank
from (irb):20
Max Length:
:023 > Skill.create!(name: "sjadfkahskdfkjsahdfkjaskjdfkjhsdjkfhksajhfjksahasdljflasjdlfkjaskldjflkasjdklfjklasjdklfjlasjdflkjasklfjsdfhkjsahkjdfhjkasdhfkjhkj", profession: Profession.first)
Profession Load (0.4ms) SELECT "professions".* FROM "professions" ORDER BY "professions"."id" ASC LIMIT $1 [["LIMIT", 1]]
(0.2ms) BEGIN
Skill Exists (0.3ms) SELECT 1 AS one FROM "skills" WHERE "skills"."name" = $1 LIMIT $2 [["name", "sjadfkahskdfkjsahdfkjaskjdfkjhsdjkfhksajhfjksahasdljflasjdlfkjaskldjflkasjdklfjklasjdklfjlasjdflkjasklfjsdfhkjsahkjdfhjkasdhfkjhkj"], ["LIMIT", 1]]
(0.3ms) ROLLBACK
ActiveRecord::RecordInvalid: Validation failed: Name is too long (maximum is 50 characters)
from (irb):23
ProfessionsController
class ProfessionsController < ApplicationController
def new
#profession = Profession.new
end
def create
#profession = Profession.find_by(name: profession_params[:name])
skill_params = get_nested_params(profession_params, :skills_attributes)
if #profession
# Save skill under existing profession
#skill = Skill.create(name: skill_params[:name], profession_id: #profession.id)
else
#profession = Profession.new(name: profession_params[:name])
if #profession.save {
saved_profession = Profession.find_by(name: profession_params[:name])
saved_profession.skills.create(name: "twitter")
# Skill.create(name: skill_params[:name], profession_id: Profession.find_by(name: profession_params[:name])).save!
}
end
end
respond_to do |format|
if #profession.save || #skill.save
format.js { render layout: false }
format.html { redirect_back fallback_location: root_path, notice: 'Profession was successfully created.' }
else
format.html { redirect_back fallback_location: root_path, notice: 'Skill was not created.' }
end
end
end
private
def profession_params
params.require(:profession).permit(:name,
skills_attributes: [:id,
:name,
:starting_date,
:profession_id,
:_destroy])
end
def get_nested_params parent_params, nested_params
nested_attrs = parent_params[nested_params]
nested_attrs[nested_attrs.keys[0]]
end
end
Updated:
Error from controller when using saved_profession.skills.create(name: "twitter")
Started POST "/professions" for 127.0.0.1 at 2017-12-19 01:50:50 +1300
Processing by ProfessionsController#create as JS
Parameters: {"utf8"=>"✓", "profession"=>{"name"=>"software", "skills_attributes"=>{"1513601431887"=>{"name"=>"rails", "_destroy"=>"false"}}}, "commit"=>"Create Profession"}
Profession Load (0.3ms) SELECT "professions".* FROM "professions" WHERE "professions"."name" = $1 LIMIT $2 [["name", "software"], ["LIMIT", 1]]
(0.1ms) BEGIN
Profession Exists (0.3ms) SELECT 1 AS one FROM "professions" WHERE "professions"."name" = $1 LIMIT $2 [["name", "software"], ["LIMIT", 1]]
SQL (0.3ms) INSERT INTO "professions" ("name", "created_at", "updated_at") VALUES ($1, $2, $3) RETURNING "id" [["name", "software"], ["created_at", "2017-12-18 12:50:50.202270"], ["updated_at", "2017-12-18 12:50:50.202270"]]
Profession Load (0.2ms) SELECT "professions".* FROM "professions" WHERE "professions"."name" = $1 LIMIT $2 [["name", "software"], ["LIMIT", 1]]
Skill Exists (0.3ms) SELECT 1 AS one FROM "skills" WHERE "skills"."name" = $1 LIMIT $2 [["name", "twitter"], ["LIMIT", 1]]
SQL (0.7ms) INSERT INTO "skills" ("profession_id", "created_at", "updated_at") VALUES ($1, $2, $3) RETURNING "id" [["profession_id", 4], ["created_at", "2017-12-18 12:50:50.205484"], ["updated_at", "2017-12-18 12:50:50.205484"]]
(0.1ms) ROLLBACK
Completed 500 Internal Server Error in 8ms (ActiveRecord: 2.2ms)
ActiveRecord::NotNullViolation (PG::NotNullViolation: ERROR: null value in column "name" violates not-null constraint
DETAIL: Failing row contains (11, null, 2017-12-14, 4, 2017-12-18 12:50:50.205484, 2017-12-18 12:50:50.205484, null).
: INSERT INTO "skills" ("profession_id", "created_at", "updated_at") VALUES ($1, $2, $3) RETURNING "id"):
app/controllers/professions_controller.rb:21:in `block in create'
app/controllers/professions_controller.rb:18:in `create'
Try modifying your get_nested_params as:
def get_nested_params(parent_params, nested_params)
parent_params # For logging purpose only
# => {"name"=>"software", "skills_attributes"=>{"1513601431887"=>{"name"=>"rails", "_destroy"=>"false"}}}
nested_params # For logging purpose only
# => :skills_attributes
nested_attrs = parent_params[nested_params]
# => {"1513601431887"=>{"name"=>"rails", "_destroy"=>"false"}}
nested_attrs.values[0] # Return this
# => {"name"=>"rails", "_destroy"=>"false"}
end
Attempting to make different orders where depending on the order there is different revisions_left which is an integer in the migration file.
I pass the params[:orderref] through a button like so <%= link_to 'Package 1', new_order_path(orderref: 1)%> and then am trying to call it in the create method like so
if params[:orderref] == "1"
#order.revisions_left = 1
elsif params[:orderref] == "2"
#order.revisions_left = 2
elsif params[:orderref] == "3"
#order.revisions_left = 3
end
However the revisions_left fails to save and am unsure why
Edit: Logs
Processing by OrderController#create as HTML
Parameters: {"utf8"=>"✓", "authenticity_token"=>"VGt/2PCPMmVnzXGm+UgHcmSvX7FEHxOoF/TfJoKf8gn3NJ0grD9JkydfswwV50GXIneFuTSClLK7cqvpsRCwRg==", "order"=>{"name"=>"sdada", "email"=>"as#tt.com", "company"=>"", "event_type"=>"Birthday", "country"=>"Brazil", "description"=>"1233 1 123 11", "order_type"=>"3", "price"=>"80"}, "commit"=>"Create Order"}
Order Load (3.0ms) SELECT "orders".* FROM "orders" WHERE "orders"."name" = $1 AND "orders"."company" = $2 AND "orders"."email" = $3 AND "orders"."event_type" = $4 AND "orders"."country" = $5 AND "orders"."description" = $6 AND "orders"."order_type" = $7 AND "orders"."price" = $8 ORDER BY "orders"."id" ASC LIMIT $9 [["name", "sdada"], ["company", ""], ["email", "as#tt.com"], ["event_type", "Birthday"], ["country", "Brazil"], ["description", "1233 1 123 11"], ["order_type", 3], ["price", 80], ["LIMIT", 1]]
(0.4ms) BEGIN
Order Exists (1.0ms) SELECT 1 AS one FROM "orders" WHERE LOWER("orders"."email") = LOWER($1) LIMIT $2 [["email", "as#tt.com"], ["LIMIT", 1]]
SQL (6.2ms) INSERT INTO "orders" ("name", "company", "email", "event_type", "country", "description", "price", "order_type", "created_at", "updated_at") VALUES ($1, $2, $3, $4, $5, $6, $7, $8, $9, $10) RETURNING "id" [["name", "sdada"], ["company", ""], ["email", "as#tt.com"], ["event_type", "Birthday"], ["country", "Brazil"], ["description", "1233 1 123 11"], ["price", 80], ["order_type", 3], ["created_at", 2017-08-03 05:26:21 UTC], ["updated_at", 2017-08-03 05:26:21 UTC]]
(71.2ms) COMMIT
(0.1ms) BEGIN
Order Exists (0.5ms) SELECT 1 AS one FROM "orders" WHERE LOWER("orders"."email") = LOWER($1) AND ("orders"."id" != $2) LIMIT $3 [["email", "as#tt.com"], ["id", 3], ["LIMIT", 1]]
SQL (0.7ms) UPDATE "orders" SET "status" = $1, "updated_at" = $2 WHERE "orders"."id" = $3 [["status", 1], ["updated_at", 2017-08-03 05:26:22 UTC], ["id", 3]]
(0.3ms) COMMIT
<%= f.time_select :exact, {ampm: true, :discard_minute=> true} %> # t.time "exact"
How do I pass the above in params?
session[:challenge_exact] = params[:exact].parse_time_select! # got nil error
session[:challenge_exact] = challenge_params[:exact]
session[:challenge_exact] = [params["challenge"]["exact(1i)"], params["challenge"]["exact(2i)"], params["challenge"]["exact(3i)"], params["challenge"]["exact(4i)"], params["challenge"]["exact(5i)"]].join(',')
None of the above work. After the challenge is created I see that exact: nil even though it was populated in the form.
Started POST "/challenges" for ::1 at 2017-05-02 08:28:31 -0400
Processing by ChallengesController#create as HTML
Parameters: {"utf8"=>"✓", "authenticity_token"=>"oN+DzJK+/GGmpTOOVYMUJQdywuENwxhmX/EVeW6NSZ3w1MctoMd/VHS39d+JasEjHujO88nLPSB2qUKEhet5yA==", "challenge"=>{"name"=>"Write 3 Gratitudes", "categorization"=>"health", "category"=>"goal", "deadline(2i)"=>"6", "deadline(3i)"=>"2", "deadline(1i)"=>"2017", "push"=>"0", "message"=>"1", "mail"=>"0", "remind"=>["mon", "thu", ""], "exact(1i)"=>"2017", "exact(2i)"=>"5", "exact(3i)"=>"2", "exact(4i)"=>"08", "exact(5i)"=>"27", "conceal"=>"0"}, "number"=>"", "email"=>"", "button"=>""}
Redirected to http://localhost:3000/signup
Completed 302 Found in 47ms (ActiveRecord: 0.0ms)
After POST challenge a person then creates a user account...
Started POST "/users" for ::1 at 2017-05-03 01:02:13 -0400
Processing by UsersController#create as HTML
Parameters: {"utf8"=>"✓", "authenticity_token"=>"4Lv5NSfH9tMnC9+t5bVC5x1d571y0jhwsgvYU3t2sp85XAnNOsHk+FCmtGcj2wJVysV6IlAIzF4jCx1hIofwsNg==", "user"=>{"name"=>"test", "last_name"=>"daddy", "email"=>"testdaddy#gmail.com", "password"=>"[FILTERED]", "time_zone"=>"Eastern Time (US & Canada)", "subscribe"=>"0"}, "button"=>""}
(0.2ms) BEGIN
User Exists (0.5ms) SELECT 1 AS one FROM "users" WHERE LOWER("users"."email") = LOWER('testdaddy#gmail.com') LIMIT 1
SQL (2.3ms) INSERT INTO "users" ("time_zone", "name", "last_name", "subscribe", "email", "password_digest", "number", "created_at", "updated_at", "activation_digest", "activated") VALUES ($1, $2, $3, $4, $5, $6, $7, $8, $9, $10, $11) RETURNING "id" [["time_zone", "Eastern Time (US & Canada)"], ["name", "test"], ["last_name", "daddy"], ["subscribe", "f"], ["email", "testdaddy#gmail.com"], ["password_digest", "$2a$10$JSSPUl0JDnUXybnAuSnEO.q5DgZscaU3hRpcM4C5L0a0aEtflzb7ne"], ["number", "15169499507"], ["created_at", "2017-05-03 05:02:14.144232"], ["updated_at", "2017-05-03 05:02:14.144232"], ["activation_digest", "$2a$10$NDtWKvxuJm/Hb9YIOzuVIuPpttCZwjsgYws6HhEcbHc.PukxXNpeLa"], ["activated", "t"]]
(18.8ms) COMMIT
(0.2ms) BEGIN
User Load (0.3ms) SELECT "users".* FROM "users" WHERE "users"."id" = $1 LIMIT 1 [["id", 16]]
# AS YOU CAN SEE WITH INSERT INTO CHALLENGES FOR SOME REASON THE SESSION PARAMS FOR EXACT ISN'T PASSING FOR EXACT
SQL (0.6ms) INSERT INTO "challenges" ("committed", "name", "categorization", "category", "deadline", "remind", "message", "user_id", "created_at", "updated_at") VALUES ($1, $2, $3, $4, $5, $6, $7, $8, $9, $10) RETURNING "id" [["committed", nil], ["name", "Write 3 Gratitudes"], ["categorization", "health"], ["category", "goal"], ["deadline", "2017-06-03"], ["remind", "---\n- mon\n- thu\n- ''\n"], ["message", "t"], ["user_id", 16], ["created_at", "2017-05-03 05:02:14.434251"], ["updated_at", "2017-05-03 05:02:14.434251"]]
ActsAsTaggableOn::Tag Load (0.6ms) SELECT "tags".* FROM "tags" INNER JOIN "taggings" ON "tags"."id" = "taggings"."tag_id" WHERE "taggings"."taggable_id" = $1 AND "taggings"."taggable_type" = $2 AND (taggings.context = 'tags' AND taggings.tagger_id IS NULL) [["taggable_id", 40], ["taggable_type", "Challenge"]]
ActsAsTaggableOn::Tag Load (0.8ms) SELECT "tags".* FROM "tags" INNER JOIN "taggings" ON "tags"."id" = "taggings"."tag_id" WHERE "taggings"."taggable_id" = $1 AND "taggings"."taggable_type" = $2 AND (taggings.context = 'tags' AND
taggings.tagger_id = 16 AND
taggings.tagger_type = 'User') [["taggable_id", 40], ["taggable_type", "Challenge"]]
(17.2ms) COMMIT
Redirected to http://localhost:3000/
How it appears in console...
exact: 2000-01-01 02:32:00 UTC>
You can access exact params like:
> params[:challenge]["exact(1i)"]
#=> "2017"
> params[:challenge]["exact(2i)"]
#=> "5"
> params[:challenge]["exact(3i)"]
#=> "2"
> params[:challenge]["exact(4i)"]
#=> "08"
> params[:challenge]["exact(5i)"]
#=> "27"
You can parse time like this:
exact_time = "#{params[:challenge]['exact(4i)']}:#{params[:challenge]['exact(5i)']}"
#=> "08:27"
> session[:challenge_exact] = Time.parse(exact_time)
#=> 2017-05-03 08:27:00 +0530
I would do:
session[:challenge_exact] = components_to_absolute(params[:exact])
def components_to_absolute(components)
DateTime.new(components['exact(1i)'].to_i,
components['exact(2i)'].to_i,
components['exact(3i)'].to_i,
components['exact(4i)'].to_i,
components['exact(5i)'].to_i)
end
When I create a new account using google authentication, it creates a account and also do the login automaticaly.
If I click logout and later login again, with the same google account, I can't login...
I get no error message :(
class OmniauthCallbacksController < Devise::OmniauthCallbacksController
def facebook
#user = User.from_omniauth(request.env["omniauth.auth"])
if #user.persisted?
sign_in_and_redirect #user, event: :authentication
set_flash_message(:notice, :success, kind: "Facebook") if is_navigational_format?
else
session["devise.facebook_data"] = request.env["omniauth.auth"]
redirect_to new_user_registration_url
end
end
def google_oauth2
#user = User.from_omniauth(request.env["omniauth.auth"])
if #user.persisted?
sign_in_and_redirect #user, event: :authentication
set_flash_message(:notice, :success, kind: "Google") if is_navigational_format?
else
session["devise.google_data"] = request.env["omniauth.auth"]
redirect_to new_user_registration_url
end
end
end
Another informations.
Here is the log when the autentication / account creation works:
Started GET "/auth/google_oauth2" for 177.207.232.141 at 2016-10-23 23:47:31 +0000
Started GET "/auth/google_oauth2/callback?state=1f3b3124e0264c1dabb3f40059d9a15a9da524553e0ec5dc&code=4/ZjqBwsoXJJXncItmMDuwPssw0ooT1RwnNjkRIfilQYc" for 177.207.232.141 at 2016-10-23 23:47:33 +0000
Processing by OmniauthCallbacksController#google_oauth2 as HTML
Parameters: {"state"=>"1f3b3124e0264c1dabb3f40059d9a15a9da524553e0ec5dc", "code"=>"4/ZjqBwsoXJJXncItmMDuwPssw0ooT1RwnNjkRIfilQYc"}
[1m[35mSubdomain Load (27.7ms)[0m SELECT "subdomains".* FROM "subdomains" WHERE "subdomains"."address" = $1 LIMIT 1 [["address", "yoga"]]
[1m[36mDomain Load (27.5ms)[0m [1mSELECT "domains".* FROM "domains" WHERE "domains"."address" = $1 LIMIT 1[0m [["address", "smartmarket.io"]]
[1m[35mUser Load (28.0ms)[0m SELECT "users".* FROM "users" WHERE "users"."provider" = $1 AND "users"."uid" = $2 ORDER BY "users"."id" ASC LIMIT 1 [["provider", "google_oauth2"], ["uid", "110174173081848856467"]]
[1m[36m (27.7ms)[0m [1mBEGIN[0m
[1m[35mUser Exists (27.8ms)[0m SELECT 1 AS one FROM "users" WHERE "users"."email" = 'diogowernik#gmail.com' LIMIT 1
[1m[36mUser Exists (27.8ms)[0m [1mSELECT 1 AS one FROM "users" WHERE "users"."email" = 'diogowernik#gmail.com' LIMIT 1[0m
[1m[35mSQL (27.9ms)[0m INSERT INTO "users" ("provider", "uid", "name", "email", "image", "encrypted_password", "created_at", "updated_at") VALUES ($1, $2, $3, $4, $5, $6, $7, $8) RETURNING "id" [["provider", "google_oauth2"], ["uid", "really?"], ["name", "Diogo Wernik"], ["email", "diogowernik#gmail.com"], ["image", "https://lh6.googleusercontent.com/-vXjHRteu8BY/AAAAAAAAAAI/AAAAAAAAB3A/_oEJPVq8h8o/photo.jpg"], ["encrypted_password", "$2a$10$6CIsOntiZxoLQfyUTfskiuys3P4u6.M0O4h/4S5zoW7EpN2KgX4Re"], ["created_at", "2016-10-23 23:47:34.023034"], ["updated_at", "2016-10-23 23:47:34.023034"]]
[1m[36mSQL (28.1ms)[0m [1mINSERT INTO "profiles" ("name", "kind", "user_id", "created_at", "updated_at") VALUES ($1, $2, $3, $4, $5) RETURNING "id"[0m [["name", "Diogo Wernik"], ["kind", "blog"], ["user_id", 5], ["created_at", "2016-10-23 23:47:34.082199"], ["updated_at", "2016-10-23 23:47:34.082199"]]
[1m[35mSQL (28.4ms)[0m INSERT INTO "user_main_profiles" ("profile_id", "user_id", "created_at", "updated_at") VALUES ($1, $2, $3, $4) RETURNING "id" [["profile_id", 5], ["user_id", 5], ["created_at", "2016-10-23 23:47:34.140877"], ["updated_at", "2016-10-23 23:47:34.140877"]]
[1m[36mUserMainProfile Load (27.7ms)[0m [1mSELECT "user_main_profiles".* FROM "user_main_profiles" WHERE "user_main_profiles"."user_id" = $1 LIMIT 1[0m [["user_id", 5]]
[1m[35m (28.1ms)[0m COMMIT
[1m[36mUser Load (27.9ms)[0m [1mSELECT "users".* FROM "users" WHERE "users"."id" = $1 ORDER BY "users"."id" ASC LIMIT 1[0m [["id", 1]]
[1m[35m (27.5ms)[0m BEGIN
[1m[36mSQL (27.9ms)[0m [1mUPDATE "users" SET "last_sign_in_at" = $1, "current_sign_in_at" = $2, "last_sign_in_ip" = $3, "current_sign_in_ip" = $4, "sign_in_count" = $5, "updated_at" = $6 WHERE "users"."id" = $7[0m [["last_sign_in_at", "2016-10-23 23:47:34.301029"], ["current_sign_in_at", "2016-10-23 23:47:34.301029"], ["last_sign_in_ip", "177.207.232.141/32"], ["current_sign_in_ip", "177.207.232.141/32"], ["sign_in_count", 1], ["updated_at", "2016-10-23 23:47:34.329926"], ["id", 5]]
[1m[35m (28.0ms)[0m COMMIT
Redirected to http://yoga.smartmarket.io/
Completed 302 Found in 636ms (ActiveRecord: 418.1ms)
[1m[36m (27.5ms)[0m [1mBEGIN[0m
[1m[35mSQL (27.7ms)[0m DELETE FROM "sessions" WHERE "sessions"."id" = $1 [["id", 11]]
[1m[36m (27.9ms)[0m [1mCOMMIT[0m
Here is when i logout and try to login again with the same account
Started GET "/auth/google_oauth2" for 177.207.232.141 at 2016-10-23 23:51:13 +0000
Started GET "/auth/google_oauth2/callback?state=ca339595a33e9e192c274a78450400a02e7edfd7f7ebb937&code=4/bQ59Fm5Fcxv_vWtBlFpMAwMoY6iig8J6bZGWFKboZms" for 177.207.232.141 at 2016-10-23 23:51:14 +0000
Processing by OmniauthCallbacksController#google_oauth2 as HTML
Parameters: {"state"=>"ca339595a33e9e192c274a78450400a02e7edfd7f7ebb937", "code"=>"4/bQ59Fm5Fcxv_vWtBlFpMAwMoY6iig8J6bZGWFKboZms"}
[1m[35mSubdomain Load (27.6ms)[0m SELECT "subdomains".* FROM "subdomains" WHERE "subdomains"."address" = $1 LIMIT 1 [["address", "yoga"]]
[1m[36mDomain Load (27.5ms)[0m [1mSELECT "domains".* FROM "domains" WHERE "domains"."address" = $1 LIMIT 1[0m [["address", "smartmarket.io"]]
[1m[35mUser Load (27.9ms)[0m SELECT "users".* FROM "users" WHERE "users"."provider" = $1 AND "users"."uid" = $2 ORDER BY "users"."id" ASC LIMIT 1 [["provider", "google_oauth2"], ["uid", "110174173081848856467"]]
[1m[36m (27.7ms)[0m [1mBEGIN[0m
[1m[35mUser Exists (28.5ms)[0m SELECT 1 AS one FROM "users" WHERE "users"."email" = 'diogowernik#gmail.com' LIMIT 1
[1m[36mUser Exists (28.0ms)[0m [1mSELECT 1 AS one FROM "users" WHERE "users"."email" = 'diogowernik#gmail.com' LIMIT 1[0m
[1m[35m (27.8ms)[0m ROLLBACK
Redirected to http://yoga.smartmarket.io/sign_up
Completed 302 Found in 271ms (ActiveRecord: 195.0ms)
Started GET "/sign_up" for 177.207.232.141 at 2016-10-23 23:51:15 +0000
Processing by Devise::RegistrationsController#new as HTML
[1m[36mSubdomain Load (27.5ms)[0m [1mSELECT "subdomains".* FROM "subdomains" WHERE "subdomains"."address" = $1 LIMIT 1[0m [["address", "yoga"]]
[1m[35mDomain Load (27.7ms)[0m SELECT "domains".* FROM "domains" WHERE "domains"."address" = $1 LIMIT 1 [["address", "smartmarket.io"]]
Rendered devise/registrations/_social.erb (0.5ms)
Rendered devise/registrations/new.html.erb within layouts/application (2.0ms)
Rendered layouts/partials/_topnavbar.html.erb (0.4ms)
Rendered layouts/partials/_sidebar.html.erb (0.1ms)
Rendered layouts/partials/_footer.html.erb (0.0ms)
Rendered layouts/partials/_alerts.erb (0.1ms)
Completed 200 OK in 251ms (Views: 165.2ms | ActiveRecord: 83.0ms)
Started GET "/api/i18n/site-pt.json" for 177.207.232.141 at 2016-10-23 23:51:16 +0000
Processing by ApiController#i18n as JSON
Parameters: {"locale"=>"site-pt"}
Rendered app/assets/i18n/site-pt.json (0.1ms)
Completed 200 OK in 35ms (Views: 5.8ms | ActiveRecord: 27.9ms)
Started GET "/assets/fontawesome/fonts/fontawesome-webfont.woff2?v=4.5.0" for 177.207.232.141 at 2016-10-23 23:51:16 +0000
Started GET "/sign_up" for 177.207.232.141 at 2016-10-23 23:51:16 +0000
Processing by Devise::RegistrationsController#new as HTML
[1m[36mSubdomain Load (27.6ms)[0m [1mSELECT "subdomains".* FROM "subdomains" WHERE "subdomains"."address" = $1 LIMIT 1[0m [["address", "yoga"]]
[1m[35mDomain Load (27.5ms)[0m SELECT "domains".* FROM "domains" WHERE "domains"."address" = $1 LIMIT 1 [["address", "smartmarket.io"]]
Rendered devise/registrations/_social.erb (0.5ms)
Rendered devise/registrations/new.html.erb within layouts/application (2.2ms)
Rendered layouts/partials/_topnavbar.html.erb (0.4ms)
Rendered layouts/partials/_sidebar.html.erb (0.1ms)
Rendered layouts/partials/_footer.html.erb (0.0ms)
Rendered layouts/partials/_alerts.erb (0.1ms)
Completed 200 OK in 231ms (Views: 144.7ms | ActiveRecord: 83.0ms)
Here is the user.rb
class User < ActiveRecord::Base
include Userable
# include DeviseTokenAuth::Concerns::User
# Include default devise modules. Others available are:
# :lockable, :timeoutable
devise :database_authenticatable, :registerable,
:recoverable, :rememberable, :trackable,
:validatable, :omniauthable # , :confirmable
validates :email, uniqueness: true
enum permission: [:guest, :admin]
after_create :create_profile!, :send_welcome_email!
before_validation :set_uid!
def self.from_omniauth(auth)
where(provider: auth.provider, uid: auth.uid).first_or_create do |user|
user.name = auth.info.name
user.provider = auth.provider
user.uid = auth.uid
user.email = auth.info.email
user.image = auth.info.image
user.password = Devise.friendly_token[0, 20]
end
end
def main_profile
user_main_profile.try :profile
end
private
def set_uid!
self.uid = 'really?'
end
def create_profile!
profile = profiles.create(
name: name,
kind: 'blog'
)
create_user_main_profile(profile_id: profile.id)
end
def send_welcome_email!
UserMailer.delay.welcome(self.id)
end
end
What I can tell is that your INSERT:
[1m[35mSQL (27.9ms)[0m INSERT INTO "users" ("provider", "uid", "name", "email", "image", "encrypted_password", "created_at", "updated_at") VALUES ($1, $2, $3, $4, $5, $6, $7, $8) RETURNING "id" [["provider", "google_oauth2"], ["uid", "really?"], ["name", "Diogo Wernik"], ["email", "diogowernik#gmail.com"], ["image", "https://lh6.googleusercontent.com/-vXjHRteu8BY/AAAAAAAAAAI/AAAAAAAAB3A/_oEJPVq8h8o/photo.jpg"], ["encrypted_password", "$2a$10$6CIsOntiZxoLQfyUTfskiuys3P4u6.M0O4h/4S5zoW7EpN2KgX4Re"], ["created_at", "2016-10-23 23:47:34.023034"], ["updated_at", "2016-10-23 23:47:34.023034"]]
is passing field ["uid", "really?"] when it should be passing ["uid", "110174173081848856467"]
So when the user tries to log via Google, it searches:
SELECT "users".* FROM "users" WHERE "users"."provider" = $1 AND "users"."uid" = $2 ORDER BY "users"."id" ASC LIMIT 1 [["provider", "google_oauth2"], ["uid", "110174173081848856467"]]
Check your user.rb to see how omniauth is getting the variables or edit your post with the content.