Rails 5.0.0.rc1
I want to have the username to downcase before save in rails 5.0.0.rc1 but some how username is nil:
user.rb:
before_save :downcase_username
def downcase_username
self.username.downcase!
end
Html:
<form action="/users" method="post">
<input type="text" name="user[username]" id="user_username" />
</form>
undefined method `downcase!' for nil:NilClass
I'm using React and I can create a user with a username no problem. I could have the username set to toLowerCase but I choose not to.
Why username is nil?
Edit (.jsx):
handleName: function(e){
this.setState({name: e.target.value});
}
<form action="/users" method="post">
<input type="text" name="user[username]" id="user_username"
value={this.state.name} onChange={this.handleName} placeholder="username" />
<button className="button small radius" type="submit">Register</button>
</form>
Devise controller:
def create
super do |resource|
resource.user[username] = params[:username]
resource.registration_id = params[:registration_id]
resource.save!
end
end
Logs:
Processing by Users::RegistrationsController#create as HTML
Parameters: {"user"=>{"username"=>"Test", "email"=>"test#example.com", "password"=>"[FILTERED]"}, "registration_id"=>"2"}
Unpermitted parameter: username
(0.2ms) BEGIN
User Exists (0.3ms) SELECT 1 AS one FROM "users" WHERE "users"."email" = $1 LIMIT $2 [["email", "test#example.com"], ["LIMIT", 1]]
(0.1ms) ROLLBACK
Completed 500 Internal Server Error in 159ms (ActiveRecord: 0.7ms)
Logs 2: # Data now saves but still getting downcase is nil
Started POST "/users" for ::1 at 2016-06-05 17:18:10 +0100
Processing by Users::RegistrationsController#create as HTML
Parameters: {"user"=>{"username"=>"Foo", "email"=>"foo#example.edu", "password"=>"[FILTERED]"}, "registration_id"=>"2"}
(0.1ms) BEGIN
User Exists (0.4ms) SELECT 1 AS one FROM "users" WHERE "users"."email" = $1 LIMIT $2 [["email", "foo#example.edu"], ["LIMIT", 1]]
SQL (1.1ms) INSERT INTO "users" ("email", "encrypted_password", "created_at", "updated_at", "username") VALUES ($1, $2, $3, $4, $5) RETURNING "id" [["email", "foo#example.edu"], ["encrypted_password", "$2a$11$TrrnP4391MeEMvn8e2JwMesU5JS0vGELx0.8eUVO.B4sDPZVdUFMy"], ["created_at", 2016-06-05 16:18:10 UTC], ["updated_at", 2016-06-05 16:18:10 UTC], ["username", "foo"]]
(0.9ms) COMMIT
(0.1ms) BEGIN
(0.1ms) ROLLBACK
Completed 500 Internal Server Error in 168ms (ActiveRecord: 5.5ms)
Update your method on user.rb to as per below:
def downcase_username
self.usernname = self.username.try(:downcase)
end
application_controller.rb
class ApplicationController < ActionController::Base
protected
def configure_permitted_parameters
# from new devise -v 4.1.1 gem
# devise_parameter_sanitizer.permit(:sign_up, keys: [:username])
# devise_parameter_sanitizer.permit(:account_update, keys: [:username])
#older version
devise_parameter_sanitizer.for(:sign_up) << [:username]
devise_parameter_sanitizer.for(:account_update) << [:username]
end
end
Related
I have
class CustomSessionsController < Devise::SessionsController
def create
#user = resource # needed for Merit
super
end
protected
def after_sign_in_path_for(resource)
#user = resource # needed for Merit
resource.update_streak
super
And
grant_on 'custom_sessions#create', badge: :streak, level: 3, temporary: true, model_name: 'User' do |user|
puts user.inspect
user.streak.count >= 3
end
But it gives the error
[merit] no target_obj found on Rule#applies?
And I can't access the model and it doesn't grant the badge or log the user. What is wrong? I followed the guide.
https://github.com/merit-gem/merit/wiki/How-to-grant-badges-on-user-using-Devise
It's doing something.
Processing by CustomSessionsController#create as HTML
Parameters: {"utf8"=>"√", "authenticity_token"=>"gqUQjF9hfzJdQqxAAQJxv7bi+kZYwuv1NWtOP0YhkbjHKwnfa5WAb/CkRZ5c+Xi5yVlnJ2v774w3XLhTa1b1sQ==", "user"=>{"email"=>"student#gmail.com", "password"=>"[FILTERED]", "remember_me"=>"0"}, "commit"=>"Log in"}
User Load (6.0ms) SELECT "users".* FROM "users" WHERE "users"."email" = $1 ORDER BY "users"."id" ASC LIMIT 1 [["email", "student#gmail.com"]]
(7.0ms) BEGIN
SQL (3.0ms) UPDATE "users" SET "last_sign_in_at" = $1, "current_sign_in_at" = $2, "sign_in_count" = $3, "updated_at" = $4 WHERE "users"."id" = $5 [["last_sign_in_at", "2018-08-09 05:38:58.345271"], ["current_sign_in_at", "2018-08-10 01:40:51.644592"], ["sign_in_count", 15], ["updated_at", "2018-08-10 01:40:51.668609"], ["id", 3]]
(25.0ms) COMMIT
Streak Load (21.0ms) SELECT "streaks".* FROM "streaks" WHERE "streaks"."user_id" = $1 LIMIT 1 [["user_id", 3]]
Redirected to http://localhost:3000/
(1.0ms) BEGIN
SQL (7.0ms) INSERT INTO "merit_actions" ("user_id", "action_method", "target_model", "target_data", "created_at", "updated_at") VALUES ($1, $2, $3, $4, $5, $6) RETURNING "id" [["user_id", 3], ["action_method", "create"], ["target_model", "custom_sessions"], ["target_data", "--- \n...\n"], ["created_at", "2018-08-10 01:40:53.539847"], ["updated_at", "2018-08-10 01:40:53.539847"]]
(8.0ms) COMMIT
Merit::Action Load (6.0ms) SELECT "merit_actions".* FROM "merit_actions" WHERE "merit_actions"."processed" = $1 [["processed", "f"]]
(3.0ms) BEGIN
SQL (2.0ms) UPDATE "merit_actions" SET "processed" = $1, "updated_at" = $2 WHERE "merit_actions"."id" = $3 [["processed", "t"], ["updated_at", "2018-08-10 01:40:53.581875"], ["id", 17]]
(20.0ms) COMMIT
User Load (2.0ms) SELECT "users".* FROM "users" WHERE "users"."id" IS NULL LIMIT 1
[merit] no target_obj found on Rule#applies?
CACHE (0.0ms) SELECT "users".* FROM "users" WHERE "users"."id" IS NULL LIMIT 1
CACHE (0.0ms) SELECT "users".* FROM "users" WHERE "users"."id" IS NULL LIMIT 1
[merit] no target_obj found on Rule#applies?
CACHE (0.0ms) SELECT "users".* FROM "users" WHERE "users"."id" IS NULL LIMIT 1
Completed 302 Found in 2567ms (ActiveRecord: 293.2ms)
Merit 2.4, Rails 4.2.
I tried
grant_on 'custom_sessions#create', badge: :streak, level: 3, temporary: true do
puts current_user.inspect
current_user.streak.count >= 3
end
But it gave
[merit] no target found: uninitialized constant CustomSession. base_target_finder.rb:13:in 'find'
error NameError (undefined local variable or method 'current_user'
I tried
grant_on 'custom_sessions#create', badge: :streak, level: 3, temporary: true, to: :itself do |user|
puts user.inspect
user.streak.count >= 3
end
def create
#custom_session = resource # needed for Merit
def after_sign_in_path_for(resource)
#custom_session = resource # needed for Merit
But it gave
[merit] no target found: uninitialized constant CustomSession. C:/ruby23/lib/ruby/gems/2.3.0/gems/merit-2.4.0/lib/merit/base_target_finder.rb:13:in `find'
true
Completed 500 Internal Server Error in 2181ms (ActiveRecord: 177.1ms)
NoMethodError (undefined method `streak' for true:TrueClass):
app/models/merit/badge_rules.rb:43:in `block in initialize'
I got it working with
grant_on 'custom_sessions#create', badge: :streak, level: 3, temporary: true, model_name: 'User', to: :itself do |user|
def create
super
#custom_session = resource # needed for Merit
But I don't know why because the /users/sign_in path does not have an :id parameter.
https://github.com/merit-gem/merit#how-merit-finds-the-target-object
Merit would fetch the Article object from the database, found by the :id param sent in that update action.
I have enabled password change notifications using
config.send_password_change_notification = true
However, currently when a user accepts an invitation triggered by Devise Invitable they are receiving a password change email.
e.g.
Started PUT "/users/invitation" for 127.0.0.1 at 2017-10-20 16:14:41 +0100
Processing by UsersController::InvitationsController#update as HTML
Parameters: {"utf8"=>"✓", "authenticity_token"=>"9gDHF+Vm6oxGPILonaQe7NSnhytoQGsOBm0eVEMziSS6J93UFnoHSwouyV9NezleulmstfcNW8Axr/nJajBBYw==", "user"=>{"invitation_token"=>"98usw1XW4w31UuCd_DzQ", "full_name"=>"example", "password"=>"[FILTERED]", "password_confirmation"=>"[FILTERED]"}, "commit"=>"Set my password"}
User Load (1.0ms) SELECT "users".* FROM "users" WHERE "users"."invitation_token" = $1 ORDER BY "users"."id" ASC LIMIT $2 [["invitation_token", "0a0787a3270a097c22a1272f49040c5c11d67b2cb222059d88d85f35e95c8d78"], ["LIMIT", 1]]
(0.2ms) BEGIN
SQL (0.6ms) UPDATE "users" SET "invitation_token" = $1, "encrypted_password" = $2, "full_name" = $3, "invitation_accepted_at" = $4, "updated_at" = $5 WHERE "users"."id" = $6 [["invitation_token", nil], ["encrypted_password", "$2a$11$qQKCx4FWQS2ARyiiGf8zdeAn7XLBa0clbWuv1cH1c1cXWbF65VMd6"], ["full_name", "example"], ["invitation_accepted_at", "2017-10-20 16:14:41.323768"], ["updated_at", "2017-10-20 16:14:41.324814"], ["id", 9]]
DeviseMailer#password_change: processed outbound mail in 1.7ms
Sent mail to example#example.com (195.9ms)
Is it possible to suppress the notification if the user is accepting an invitation but continue to send it for other password change events?
Environment info:
Rails 5.1.4
devise (4.3.0, 4.2.1)
devise_invitable (1.7.2)
thank you for pointing me in the right direction, here is my take on this
def send_password_change_notification
super unless accepting_invitation?
end
accepting_invitation? is a variable set on the beginning of the process
As a bonus, it bugged me that when you ask for a password recover it would prompt you with a success message and don't do anything, with this it would prompt with an error message.
[:en, :errors, :messages, :invitation_active] on your locales or just use default :not_found
def send_reset_password_instructions
if invited_to_sign_up?
self.errors.add :email, :invitation_active
else
super
end
end
OK, figured this out.
Add the following to app/models/user.rb
def send_devise_notification(notification, *args)
unless(notification == :password_change && sign_in_count.zero?)
super
end
end
I am using Rails 4.1.14, Ruby 2.1.6, Devise 3.2.4 and Devise_invitable 1.3.6.
The issue I am having is once a new user I invited presses the accept invitation link in the email they received, it gets stuck in a redirect loop. I can't figure out why.
These are the server logs for the entire operation (note that the bulk of the first part of the log corresponds to the logic I omit below - but I left it in case it tells something interesting) :
Started GET "/users/invitation/accept?invitation_token=qANzitr64dxzxG9dSsMU" for 127.0.0.1 at 2015-12-12 04:51:29 -0500
Processing by Users::InvitationsController#edit as HTML
Parameters: {"invitation_token"=>"qANzitr6"}
User Load (4.0ms) SELECT "users".* FROM "users" WHERE "users"."invitation_token" = 'qANzitr6' ORDER BY "users"."id" ASC LIMIT 1
User Load (1.9ms) SELECT "users".* FROM "users" WHERE "users"."id" = $1 LIMIT 1 [["id", 1]]
Member Load (3.8ms) SELECT "members".* FROM "members" WHERE "members"."email" = 'def#test.com' LIMIT 1
Membership Load (88.3ms) SELECT "memberships".* FROM "memberships" WHERE "memberships"."member_id" = 115 LIMIT 1
Connection Load (14.8ms) SELECT "connections".* FROM "connections" WHERE "connections"."membership_id" = 173 ORDER BY "connections"."id" ASC LIMIT 1
(2.3ms) BEGIN
SQL (3.4ms) UPDATE "memberships" SET "invited_id" = $1, "member_id" = $2, "relative_type" = $3, "updated_at" = $4 WHERE "memberships"."id" = 173 [["invited_id", 83], ["member_id", nil], ["relative_type", 1], ["updated_at", "2015-12-12 09:51:30.038439"]]
(1.8ms) COMMIT
Membership Load (2.3ms) SELECT "memberships".* FROM "memberships" WHERE "memberships"."user_id" = $1 AND "memberships"."invited_id" = 83 ORDER BY "memberships"."id" ASC LIMIT 1 [["user_id", 1]]
FamilyTree Load (1.7ms) SELECT "family_trees".* FROM "family_trees" WHERE "family_trees"."user_id" = $1 LIMIT 1 [["user_id", 83]]
Membership Load (3.7ms) SELECT "memberships".* FROM "memberships" WHERE "memberships"."user_id" = 83 AND "memberships"."invited_id" = 1 AND "memberships"."family_tree_id" = 85 AND "memberships"."relation" = 'wife' AND "memberships"."relative_type" = 1 LIMIT 1
(33.0ms) BEGIN
SQL (37.9ms) INSERT INTO "memberships" ("created_at", "family_tree_id", "invited_id", "relation", "relative_type", "updated_at", "user_id") VALUES ($1, $2, $3, $4, $5, $6, $7) RETURNING "id" [["created_at", "2015-12-12 09:51:30.105734"], ["family_tree_id", 85], ["invited_id", 1], ["relation", "wife"], ["relative_type", 1], ["updated_at", "2015-12-12 09:51:30.105734"], ["user_id", 83]]
Connection Exists (11.7ms) SELECT 1 AS one FROM "connections" INNER JOIN "memberships" ON "memberships"."id" = "connections"."membership_id" WHERE (memberships.invited_id = 83) LIMIT 1
(2.1ms) COMMIT
(1.6ms) BEGIN
SQL (3.7ms) UPDATE "connections" SET "invited_membership_id" = $1, "invited_user_id" = $2, "request_status" = $3, "responded_at" = $4, "updated_at" = $5 WHERE "connections"."id" = 127 [["invited_membership_id", 174], ["invited_user_id", 83], ["request_status", 1], ["responded_at", "2015-12-12 09:51:30.167563"], ["updated_at", "2015-12-12 09:51:30.172215"]]
(1.9ms) COMMIT
SQL (2.3ms) DELETE FROM "members" WHERE "members"."id" = 115
Rendered shared/_footer.html.erb (4.5ms)
Rendered users/invitations/edit.html.erb within layouts/devise (48.6ms)
Completed 200 OK in 1689ms (Views: 1405.9ms | ActiveRecord: 222.2ms)
Started PUT "/users/invitation" for 127.0.0.1 at 2015-12-12 04:51:53 -0500
Processing by UsersController#update as HTML
Parameters: {"utf8"=>"✓", "user"=>{"invitation_token"=>"qANzitr6", "gender"=>"female", "invitation_relation"=>"wife", "full_name"=>"My Wife", "password"=>"[FILTERED]", "password_confirmation"=>"[FILTERED]"}, "commit"=>"Register", "id"=>"invitation"}
Completed 401 Unauthorized in 8ms (ActiveRecord: 0.0ms)
Started GET "/users/login" for 127.0.0.1 at 2015-12-12 04:51:53 -0500
Processing by UsersController#show as HTML
Parameters: {"id"=>"login"}
Completed 401 Unauthorized in 1ms (ActiveRecord: 0.0ms)
Started GET "/users/login" for 127.0.0.1 at 2015-12-12 04:51:53 -0500
Processing by UsersController#show as HTML
Parameters: {"id"=>"login"}
Completed 401 Unauthorized in 1ms (ActiveRecord: 0.0ms)
This is my Users::InvitationsController#Edit
def edit
# Some logic that I know works and is irrelevant to this question.
# below is lifted directly from the `edit` action within the gem itself.
set_minimum_password_length if respond_to? :set_minimum_password_length
resource.invitation_token = params[:invitation_token]
render :edit
end
Then I specified an accept_resource method like the docs suggested I do if I want anything special to happen after or before the invitation is sent.
def accept_resource
resource = resource_class.accept_invitation!(update_resource_params)
resource.confirm!
resource
end
I assumed that part of the reason this must be happening is that I am stuck in a loop where the user's account wasn't confirmed after they accepted....hence that override.
Here is my User.rb:
class User < ActiveRecord::Base
devise :database_authenticatable, :registerable,
:recoverable, :rememberable, :trackable, :validatable, :invitable, :confirmable
end
What could be causing this?
I have a Rails app with 3 sign up button links on the home page.
Each has it's own plan assigned to it. Two of them go to a basic form while the third goes to a form with credit card details, handled by Stripe. The forms and Users are handled by Devise.
The plans seem to be setup correctly and are seen in the rails console however, when I go to sign up, to any of them, only the email address and password is captured, and NO plan_id is assigned.
I've noticed when previewing the form pages locally that the url at the top doesn't change to the specific form url, i.e /users/sign_up?plan=3 for example, but instead shows the form but stays on the homepage url? I'm confused because the server seems to recognise which link i'm clicking on and which plan needs to be assigned?? Please Help!!
Started GET "/users/sign_up?plan=3" for 124.149.46.152 at 2015-08-21 06:32:19 +0000
Cannot render console from 124.149.46.152! Allowed networks: 127.0.0.1, ::1, 127.0.0.0/127.255.255.255
Processing by Users::RegistrationsController#new as HTML
Parameters: {"plan"=>"3"}
Rendered devise/registrations/_paid.html.erb (8.1ms)
Rendered devise/shared/_links.html.erb (0.3ms)
Rendered devise/registrations/new.html.erb within layouts/application (11.6ms)
Completed 200 OK in 154ms (Views: 151.7ms | ActiveRecord: 0.0ms)
console User.last
=> #<User id: 7, email: "testemail1#test.com", encrypted_password: "$2a$10$.EldkZ3KUdnz4u1dvIMkXO7U6GnAnrGNYomdITKqup....", reset_password_token: nil, reset_password_sent_at: nil, remember_created_at: nil, sign_in_count: 1, current_sign_in_at: "2015-08-21 07:05:34", last_sign_in_at: "2015-08-21 07:05:34", current_sign_in_ip: "124.149.46.152", last_sign_in_ip: "124.149.46.152", created_at: "2015-08-21 07:05:34", updated_at: "2015-08-21 07:05:34", plan_id: nil, stripe_customer_token: nil>
and this is my application_controller.rb
class ApplicationController < ActionController::Base
# Prevent CSRF attacks by raising an exception.
# For APIs, you may want to use :null_session instead.
protect_from_forgery with: :exception
before_filter :configure_permitted_parameters, if: :devise_controller?
protected
def configure_permitted_parameters
devise_parameter_sanitizer.for(:sign_up) { |u| u.permit(:name, :stripe_card_token, :email, :password, :password_confirmation }
end
end
development log
Started POST "/users" for 124.149.46.152 at 2015-08-21 07:31:57 +0000
Cannot render console from 124.149.46.152! Allowed networks: 127.0.0.1, ::1, 127.0.0.0/127.255.255.255
Processing by Users::RegistrationsController#create as HTML
Parameters: {"utf8"=>"✓", "authenticity_token"=>"mA18/inejU2zEZiYXJq1xEtguLOEWnIV9UBozrHyXKPp2/2n9Ls7Km4+fCuZBL51EHUxSE+QJFRdbgW1fbMyew==", "user"=>{"email"=>"test10#gmail.com", "password"=>"[FILTERED]", "password_confirmation"=>"[FILTERED]"}, "commit"=>"Sign up"}
[1m[35m (0.4ms)[0m begin transaction
[1m[36mUser Exists (0.2ms)[0m [1mSELECT 1 AS one FROM "users" WHERE "users"."email" = 'test10#gmail.com' LIMIT 1[0m
[1m[35mSQL (0.6ms)[0m INSERT INTO "users" ("email", "encrypted_password", "created_at", "updated_at") VALUES (?, ?, ?, ?) [["email", "test10#gmail.com"], ["encrypted_password", "$2a$10$4cjIpysvXyckg0j4Kxzx9eqR9vVzqcmaQZPLdCC0X2jEik2MG/KrK"], ["created_at", "2015-08-21 07:31:57.381867"], ["updated_at", "2015-08-21 07:31:57.381867"]]
[1m[36m (19.3ms)[0m [1mcommit transaction[0m
[1m[35m (0.2ms)[0m begin transaction
[1m[36mSQL (0.5ms)[0m [1mUPDATE "users" SET "last_sign_in_at" = ?, "current_sign_in_at" = ?, "last_sign_in_ip" = ?, "current_sign_in_ip" = ?, "sign_in_count" = ?, "updated_at" = ? WHERE "users"."id" = ?[0m [["last_sign_in_at", "2015-08-21 07:31:57.405089"], ["current_sign_in_at", "2015-08-21 07:31:57.405089"], ["last_sign_in_ip", "124.149.46.152"], ["current_sign_in_ip", "124.149.46.152"], ["sign_in_count", 1], ["updated_at", "2015-08-21 07:31:57.406791"], ["id", 8]]
[1m[35m (19.7ms)[0m commit transaction
Redirected to https://socialplayground-portal-runpixelrun.c9.io/
Completed 302 Found in 136ms (ActiveRecord: 40.9ms)
Started GET "/" for 124.149.46.152 at 2015-08-21 07:31:57 +0000
Cannot render console from 124.149.46.152! Allowed networks: 127.0.0.1, ::1, 127.0.0.0/127.255.255.255
Processing by PagesController#home as HTML
[1m[36mPlan Load (0.4ms)[0m [1mSELECT "plans".* FROM "plans" WHERE "plans"."id" = ? LIMIT 1[0m [["id", 1]]
[1m[35mPlan Load (0.2ms)[0m SELECT "plans".* FROM "plans" WHERE "plans"."id" = ? LIMIT 1 [["id", 2]]
[1m[36mPlan Load (0.2ms)[0m [1mSELECT "plans".* FROM "plans" WHERE "plans"."id" = ? LIMIT 1[0m [["id", 3]]
Rendered pages/home.html.erb within layouts/application (1.0ms)
[1m[35mUser Load (0.4ms)[0m SELECT "users".* FROM "users" WHERE "users"."id" = ? ORDER BY "users"."id" ASC LIMIT 1 [["id", 8]]
Completed 200 OK in 210ms (Views: 207.3ms | ActiveRecord: 1.2ms)
[1m[36mUser Load (0.7ms)[0m [1mSELECT "users".* FROM "users" ORDER BY "users"."id" DESC LIMIT 1[0m
Started DELETE "/users/sign_out" for 124.149.46.152 at 2015-08-21 07:35:08 +0000
Cannot render console from 124.149.46.152! Allowed networks: 127.0.0.1, ::1, 127.0.0.0/127.255.255.255
Processing by Devise::SessionsController#destroy as HTML
Parameters: {"authenticity_token"=>"p1LtsYqgP4SPYiiAh8/l1/XPNc888HMVob3thu5Y093WhGzoV8WJ41JNzDNCUe5mrtq8NPc6JVQJk4D9Ihm9BQ=="}
[1m[36mUser Load (0.2ms)[0m [1mSELECT "users".* FROM "users" WHERE "users"."id" = ? ORDER BY "users"."id" ASC LIMIT 1[0m [["id", 8]]
[1m[35m (0.1ms)[0m begin transaction
[1m[36m (0.1ms)[0m [1mcommit transaction[0m
Redirected to https://socialplayground-portal-runpixelrun.c9.io/
Completed 302 Found in 10ms (ActiveRecord: 0.4ms)
Started GET "/" for 124.149.46.152 at 2015-08-21 07:35:08 +0000
Cannot render console from 124.149.46.152! Allowed networks: 127.0.0.1, ::1, 127.0.0.0/127.255.255.255
Processing by PagesController#home as HTML
[1m[35mPlan Load (0.2ms)[0m SELECT "plans".* FROM "plans" WHERE "plans"."id" = ? LIMIT 1 [["id", 1]]
[1m[36mPlan Load (0.1ms)[0m [1mSELECT "plans".* FROM "plans" WHERE "plans"."id" = ? LIMIT 1[0m [["id", 2]]
[1m[35mPlan Load (0.1ms)[0m SELECT "plans".* FROM "plans" WHERE "plans"."id" = ? LIMIT 1 [["id", 3]]
Rendered pages/home.html.erb within layouts/application (0.8ms)
Completed 200 OK in 206ms (Views: 203.3ms | ActiveRecord: 0.5ms)
/registrations_controller.rb
class Users::RegistrationsController < Devise::RegistrationsController
before_filter :select_plan, only: :new
def create
super do |resource|
if params[:plan]
resource.plan_id = params[:plan]
if resource.plan_id == 3
resource.save_with_payment
else
resource.save
end
end
end
end
private
def select_plan
unless params[:plan] && (params[:plan] == '1' || params[:plan] == '2' || params[:plan] == '3')
flash[:notice] = "Please select a valid membership plan."
redirect_to root_url
end
end
end
To allow plan_id to be save you need to add it in devise signup parameters. You can do this by adding following into your application controller
before_filter :configure_permitted_parameters, if: :devise_controller?
def configure_permitted_parameters
devise_parameter_sanitizer.for(:sign_up) { |u| u.permit(:email, :password_confirmation, :plan_id) }
end
I have this in the Model:
after_create do |comment|
CommentMailer.comment_email(self).deliver
end
This in CommentMailer:
class CommentMailer < ActionMailer::Base
helper ActionView::Helpers::UrlHelper
include CommentHelper
helper :comment
def comment_email(user, comment, commentable)
mail(to: user.email,
subject: "You have left a comment",
from: "comments#lumeo.com",
bcc: "brian#lumeo.com")
end
end
And this in CommentHelper:
module CommentHelper
def find_commentable
#comment = Comment.find(params[:comment])
params.each do |name, value|
if name =~ /(.+)_id$/
return $1.classify.constantize.find(value)
end
end
nil
end
end
I'm getting this error:
Started POST "/requests/6/comments" for 127.0.0.1 at 2012-11-30 17:28:55 -0800
Processing by CommentsController#create as HTML
Parameters: {"utf8"=>"✓", "authenticity_token"=>"R62NH5/EE34FPapEqy7mfpa0wKz18GtSdhH8MGYq2Ec=", "comment"=>{"content"=>"post", "show"=>"true"}, "commit"=>"Create Comment", "request_id"=>"6"}
User Load (0.3ms) SELECT "users".* FROM "users" WHERE "users"."id" = 2 ORDER BY users.created_at DESC LIMIT 1
Request Load (0.3ms) SELECT "requests".* FROM "requests" WHERE "requests"."id" = $1 LIMIT 1 [["id", "6"]]
CACHE (0.0ms) SELECT "requests".* FROM "requests" WHERE "requests"."id" = $1 LIMIT 1 [["id", "6"]]
(0.1ms) BEGIN
SQL (0.4ms) INSERT INTO "comments" ("commentable_id", "commentable_type", "content", "created_at", "show", "updated_at", "user_id") VALUES ($1, $2, $3, $4, $5, $6, $7) RETURNING "id" [["commentable_id", 6], ["commentable_type", "Request"], ["content", "post"], ["created_at", Sat, 01 Dec 2012 01:28:55 UTC +00:00], ["show", true], ["updated_at", Sat, 01 Dec 2012 01:28:55 UTC +00:00], ["user_id", 2]]
(0.2ms) ROLLBACK
Completed 500 Internal Server Error in 136ms
ArgumentError (wrong number of arguments (1 for 3)):
app/mailers/comment_mailer.rb:5:in `comment_email'
app/models/comment.rb:27:in `block in <class:Comment>'
app/controllers/comments_controller.rb:22:in `create'
Looks like simple typos.
Line 7, as noted in the exception:
commentable = #comment.commentable
So, the issues:
You're calling #comment.commentabe, but #comment is nil
Hence the error: undefined method 'commentable' for nil:NilClass
#comment is nil in your mailer method because you're passing it in as comment NOT #comment, yet you're trying to reference it as #comment.
Also, why are you passing in commentable as a parameter, but on line 7 you're setting commentable again - this is redundant? Just use the already available commentable variable that you're passing in as a param. In fact, you seem to be doing this with several variables, yet I can't tell (because you don't show the mailer template) whether or not you're actually using them.
It could be that you could use something simpler like:
So, this should (probably) work:
def comment_email(user, comment, commentable)
mail(to: user.email,
subject: "You have left a comment",
from: "comments#lumeo.com",
bcc: "brian#lumeo.com")
end
If you post your mail template (so I can see what the body of the email looks like) I can help you get the variables into the template.