ActiveModel::ForbiddenAttributesError Ruby On Rails - ruby-on-rails

I created a project in Ruby On rails and I have controller user like this:
class UsersController < ApplicationController
before_action :set_user, only: [:edit, :update]
def new
#user = User.new
end
def create
#user = User.new(params[:user])
if #user.save
redirect_to root_url, :notice => "Signed up!"
else
render "new"
end
end
private
def user_params
params.require(:user).permit(:email, :password, :password_confirmation)
end
end
And model user like this:
class User < ActiveRecord::Base
#attr_accessible :email, :password, :password_confirmation
attr_accessor :password
before_save :encrypt_password
def self.authenticate(email, password)
user = find_by_email(email)
if user && user.password_hash == BCrypt::Engine.hash_secret(password, user.password_salt)
user
else
nil
end
end
def encrypt_password
if password.present?
self.password_salt = BCrypt::Engine.generate_salt
self.password_hash = BCrypt::Engine.hash_secret(password, password_salt)
end
end
end
And when I try to create new user i get Error: ActiveModel::ForbiddenAttributesError
Parameters:
{"utf8"=>"✓",
"authenticity_token"=>"74Mhbpn9FF/tY/cgfuVmX7ribN4rOkkdUjSgbLNsces=",
"user"=>{"email"=>"henio180#interia.pl",
"password"=>"[FILTERED]",
"password_confirmation"=>"[FILTERED]"},
"button"=>""}
I am using Ruby on Rails 4.0.3.

In your create method change:
#user = User.new(params[:user])
to
#user = User.new(user_params)
Although you created the method correctly to set up strong parameters, you are not actually using it. There is good detail about using strong parameters in the Rails guide: http://guides.rubyonrails.org/action_controller_overview.html#strong-parameters

Related

Ruby on Rails: How to store data in two tables following the creation of a record in one?

I have two database tables Users and Accounts, when a new user is created their primary email address that they will use to login is stored in the Users table. What I want to do is also store a copy of their primary email address in the Accounts table, as this table will be used to store the email addresses of that user.
I have tried the following in my users_controller:
class UsersController < ApplicationController
def index
#users = User.all
end
def show
#user = User.find(params[:id])
end
def new
#user = User.new
end
def edit
#user = User.find(params[:id])
end
def create
#user = User.new(user_params)
if #user.save
session[:user_id] = #user.id
#account = Account.new(email: params[:primaryemailaddress], user_id: session[:user_id])
redirect_to #user
else
render 'new'
end
end
def update
#user = User.find(params[:id])
if #user.update(user_params)
redirect_to #user
else
render 'edit'
end
end
def destroy
#user = User.find(params[:id])
#user.destroy
redirect_to users_path
end
private
def user_params
params.require(:user).permit(:title, :firstname, :surname, :housenumber, :street, :city, :postcode, :organisation, :primaryemailaddress, :password)
end
end
And the following in my User model:
class User < ActiveRecord::Base
has_many :accounts
accepts_nested_attributes_for :accounts
validates :primaryemailaddress, presence: true
has_secure_password
end
So, as you can see in the create method in the users_controller, I am trying to create a new record in the Accounts table using the primary email address the user has entered on the registration form.
Can someone please tell me where I am going wrong?
Please try with below modification
def create
#user = User.new(user_params)
if #user.save
session[:user_id] = #user.id
#account = Account.create(email: params[:user][:primaryemailaddress], user_id: session[:user_id])
redirect_to #user
else
render 'new'
end
end

Cannot retrieve attr_accessor in Rails 4

I'm working on a Ruby on Rails project and I have two models:
1. User
2. Merchant
their relationships are:
User has_one :merchant
Merchant belongs_to :user
then in my user.rb
attr_accessor :merchant_name
after_create :create_merchant
def create_merchant
create_merchant(name: merchant_name)
end
In my user's form:
= form_for #user do |f|
= f.text_field :merchant_name
= f.text_field :email
= f.text_field :password
the problem is the user and a merchant has been created but the merchant's name is nil
In my Account::RegistrationsController
class Account::RegistrationsController < Devise::RegistrationsController
protected
def after_sign_up_path_for(resource)
account_users_path
end
private
def registration_params
params.require(:user).permit(:merchant_name)
end
end
I'm getting this error:
Processing by Account::RegistrationsController#create as HTML
Parameters: {"utf8"=>"✓", "authenticity_token"=>"ht8vHG8I4bz2ylt+mtLC7hilQnK3VnYtcHgSNv8nSeg=", "user"=>{"merchant_name"=>"Zara 123", "email"=>"allen.chun#hotmail.com",
"password"=>"[FILTERED]",
"password_confirmation"=>"[FILTERED]"}, "commit"=>"Sign Up"}
Unpermitted parameters: merchant_name
I wouldn't override the create_merchant method if I were you, try something like this:
after_create -> { create_merchant!(:name => self.merchant_name) }
and make sure your merchant_name is permitted in the users controller, something like this:
def create
#user = User.new(user_params)
if #user.save
redirect_to #user
else
render :new
end
end
private
def user_params
params.require(:user).permit(:merchant_name, :email, :password, :password_confirmation)
end
Perhaps it should be
attr_accessor :merchant_name
after_create :create_merchant
def create_merchant
build_merchant(name: merchant_name)
save
end
create_association hasn't supported in rails 4
Also don't forget to permit merchant_name. According to this info:
class Account::RegistrationsController < Devise::RegistrationsController
before_action :configure_permitted_parameters
protected
def after_sign_up_path_for(resource)
account_users_path
end
def configure_permitted_parameters
devise_parameter_sanitizer.for(:sign_up) << :merchant_name
end
end

authentication fails after submiting - rails 4

I am trying to make simple authentication/registration ruby app. I am using BCrypt gem for crypting and it now gives me some problems. When I press submit button it throws
undefined method `password_salt=' for #<User:0x007f93c36bc570>
Ok, so I red that this code should be places from model to coontroler, but that gave me this er
undefined local variable or method `encrypt_password' for #<User:0x007f93c5f35f10>
I have tried rake db:migrate and restarting app also
git repo: https://github.com/pumpurs/auth
(code im talking about)
def encrypt_password
if password.present?
self.password_salt = BCrypt::Engine.generate_salt
self.password_hash = BCrypt::Engine.hash_secret(password, password_salt)
end
end
controller:
class UsersController < ApplicationController
def new
#user = User.new
end
def create
#user = User.new(params[:user].permit(:password, :email, :password_confirmation))
if #user.save
redirect_to root_url, :notice => "Signed up!"
else
render "new"
end
end
private
def user_params
params.require(:user).permit(:password, :email, :password_confirmation)
end
end
model file:
class User < ActiveRecord::Base
attr_accessor :password, :salt
before_save :encrypt_password
validates_confirmation_of :password
validates_presence_of :password, :on => :create
validates_presence_of :email
validates_uniqueness_of :email
def encrypt_password
if password.present?
self.password_salt = BCrypt::Engine.generate_salt
self.password_hash = BCrypt::Engine.hash_secret(password, password_salt)
end
end
end
Add
attr_accessor :password_salt
in model?
Why don't use Devise or another authentication gem?

Passing email address from params to a model method in Rails 3.2.11

In the following code I get "wrong number of arguments (0 for 2)" for the following line
user = User.authenticate(params[:email], params[:password])
if params[:email] contains # character. Without the # character everything works fine, I don't have a single idea how to solve it.
I tried to give an email as string like user = User.authenticate("test#test.com", params[:password]) and I don't get the error.
Could anyone help with it?
My code:
Controller:
class SessionsController < ApplicationController
def new
end
def create
user = User.authenticate(params[:email], params[:password])
if user
session[:user_id] = user.id
redirect_to root_url, :notice => "Logged in!"
else
flash.now.alert = "Invalid email or password"
render "new"
end
end
end
Model:
class User < ActiveRecord::Base
attr_accessor :password
before_save :encrypt_password
validates_confirmation_of :password
validates_presence_of :password, :on => :create
validates_presence_of :email
validates_uniqueness_of :email
def encrypt_password
if password.present?
self.password_salt = BCrypt::Engine.generate_salt
self.password_hash = BCrypt::Engine.hash_secret(password, password_salt)
end
end
def self.authenticate(email, password)
user = find_by_email(email)
if user && user.password_hash == BCrypt::Engine.hash_secret ↵
(password, user.password_salt)
user
else
nil
end
end
end
Try:
User.authenticate(params[:email].to_s, params[:password])
This is because your email type is string and you are passing it a hash in the method.

User.authenticate method returning nil in Rails 3?

The User.authenticate method is returning nil even though the user exists in the database with the correct email and password. This happens when calling the authenticate method from the Create action in the Sessions controller or from the Rails Console (irb).
Any help with this problem will be greatly appreciated.
class SessionsController < ApplicationController
def new
end
def create
user = User.authenticate(params[:session][:email],
params[:session][:password])
if user.nil?
flash.now[:error] = "Invalid email/password combination"
render 'new'
else
sign_in user
redirect_to user
end
end
def destroy
sign_out
render 'pages/options'
end
end
Here is my User model:
class User < ActiveRecord::Base
attr_accessor :password
attr_accessible :first_name, :last_name, :email, :password, :password_confirmation,
:account_type, :email_confirmed, :weight
validates :password, :presence => true,
:confirmation => true,
:length => { :within => 6..40 }
before_save :encrypt_password
def has_password?(submitted_password)
encrypted_password == encrypt(submitted_password)
end
def self.authenticate(email, submitted_password)
user = find_by_email(email)
return nil if user.nil?
return user if user.has_password?(submitted_password)
end
def self.authenticate_with_salt(id, cookie_salt)
user = find_by_id(id)
(user && user.salt == cookie_salt) ? user : nil
end
private #################################################
def encrypt_password
self.salt = make_salt if new_record?
self.encrypted_password = encrypt(password)
end
def encrypt(string)
secure_hash("#{salt}--#{string}")
end
def make_salt
secure_hash("#{Time.now.utc}--#{password}")
end
def secure_hash(string)
Digest::SHA2.hexdigest(string)
end
def generate_email_conf_code
email_conf_code = secure_hash("#{Time.now.utc}")
self.email_conf_code = email_conf_code
end
end
Try to check your server log. You can also monitor them directly on the terminal. Look for the session email received on the server. It looks something like this on Rails 3.1.1
Parameters: {"session"=>{"email"=>"xxx#yyy.com", "password"=>"[FILTERED]"}}
See that you're getting the email correctly. If not, I guess you know what to do.
does your database store a password_digest or encrypted_password column? Older tutorials by michael hartl used password_digest, now they seem they are encrypted_password.

Resources