"Password can't be blank" Rails Rails 4.2.4 - ruby-on-rails

Like other posts, I'm getting an error "Password can't be blank" even though the password is filled in. I've added this wrap_parameters :user, include: [:username, :email, :password, :password_confirmation] to my UsersController but with no luck. Here is my Controller:
class UsersController < ApplicationController
before_action :set_user, only: [:show, :edit, :update, :destroy]
wrap_parameters :user, include: [:username, :email, :password, :password_confirmation]
# GET /users
# GET /users.json
def index
#users = User.all
end
# GET /users/1
# GET /users/1.json
def show
end
# GET /users/new
def new
#user = User.new
end
# GET /users/1/edit
def edit
end
# POST /users
# POST /users.json
def create
#user = User.new(user_params)
puts "*********"
puts user_params
respond_to do |format|
if #user.save
format.html { redirect_to #user, notice: 'User was successfully created.' }
format.json { render :show, status: :created, location: #user }
else
format.html { render :new }
format.json { render json: #user.errors, status: :unprocessable_entity }
end
end
end
# PATCH/PUT /users/1
# PATCH/PUT /users/1.json
def update
respond_to do |format|
if #user.update(user_params)
format.html { redirect_to #user, notice: 'User was successfully updated.' }
format.json { render :show, status: :ok, location: #user }
else
format.html { render :edit }
format.json { render json: #user.errors, status: :unprocessable_entity }
end
end
end
# DELETE /users/1
# DELETE /users/1.json
def destroy
#user.destroy
respond_to do |format|
format.html { redirect_to users_url, notice: 'User was successfully destroyed.' }
format.json { head :no_content }
end
end
private
# Use callbacks to share common setup or constraints between actions.
def set_user
#user = User.find(params[:id])
end
# Never trust parameters from the scary internet, only allow the white list through.
def user_params
params.require(:user).permit(:username, :email, :password, :password_confirmation )
end
end
And here is my Model:
class User < ActiveRecord::Base
has_secure_password
attr_accessor :username, :email, :password, :password_confirmation
EMAIL_REGEX = /[A-Z0-9._%+-]+#[A-Z0-9.-]+\.[A-Z]{2,4}/i
validates :username, :presence => true, :uniqueness => true, :length => { :in => 3..20 }
validates :email, :presence => true, :uniqueness => true, :format => EMAIL_REGEX
validates :password, :confirmation => true #password attr
validate :confirm_password_match
validates_length_of :password, :in => 8..20, :on => :create
before_save :encrypt_password, :prep_data
after_save :clear_password
def prep_data
self.email = email.downcase
self.username = username.downcase
end
def encrypt_password
if password.present?
self.password_salt = BCrypt::Engine.generate_salt
self.password_digest = BCrypt::Engine.hash_secret(password, password_salt)
end
end
def clear_password
self.password = nil
end
def confirm_password_match
if self.password != self.password_confirmation
errors.add(:password, "Passwords must match")
errors.add(:password_confirmation, "Passwords must match")
end
end
end
Any help would be appreciated ...

Related

Ruby on Rails NoMethodError in FoodItemsController#create

This is the error I am getting when I hit submit on my form for uploading an image. Can anyone help me out? I feel like the JSON serialize isnt working. which is causing the error.
class FoodItem < ApplicationRecord
mount_uploader :image, ImageUploader
serialize :image, JSON # If you use SQLite, add this line
belongs_to :user, optional: true
validates :name, :description, :resturant, :glutenfree, :vegan, presence: true
validates :description, length: {maximum: 1000, too_long: "%{count} characters is the maximum allowed"}
validates :title, length: {maximum: 140, too_long: "%{count} characters is the maximum allowed"}
end
here is my food controller,
class FoodItemsController < ApplicationController
before_action :set_food_item, only: %i[ show edit update destroy ]
before_action :authenticate_user!, except: [:index, :show]
# GET /food_items or /food_items.json
def index
#food_items = FoodItem.all.order("created_at desc")
end
# GET /food_items/1 or /food_items/1.json
def show
end
# GET /food_items/new FoodItem.new
def new
#food_item = current_user.food_items.build
end
# GET /food_items/1/edit
def edit
end
# POST /food_items or /food_items.json FoodItem.new(food_item_params)
def create
#food_item = current_user.food_items.build(food_item_params)
respond_to do |format|
if #food_item.save
format.html { redirect_to food_items_url(#food_item), notice: "Food item was successfully created." }
format.json { render :show, status: :created, location: #food_item }
else
format.html { render :new, status: :unprocessable_entity }
format.json { render json: #food_item.errors, status: :unprocessable_entity }
end
end
end
# PATCH/PUT /food_items/1 or /food_items/1.json
def update
respond_to do |format|
if #food_item.update(food_item_params)
format.html { redirect_to food_items_url(#food_item), notice: "Food item was successfully updated." }
format.json { render :show, status: :ok, location: #food_item }
else
format.html { render :edit, status: :unprocessable_entity }
format.json { render json: #food_item.errors, status: :unprocessable_entity }
end
end
end
# DELETE /food_items/1 or /food_items/1.json
def destroy
#food_item.destroy
respond_to do |format|
format.html { redirect_to food_items_url, notice: "Food item was successfully destroyed." }
format.json { head :no_content }
end
end
# Use callbacks to share common setup or constraints between actions.
def set_food_item
#food_item = FoodItem.find(params[:id])
end
# Only allow a list of trusted parameters through.
def food_item_params
params.require(:food_item).permit(:name, :foodtype, :description, :ingrediants, :resturant, :glutenfree, :vegan, :image)
end
end
I believe the error is being caused by the image not being serialized to json because when I got to /public/images/tmp the images are being uploaded.
run rails db:migrate if title field not found foodItem_table
add title into food_item_params
def food_item_params
params.require(:food_item).permit(:name, :foodtype, :description, :ingrediants, :resturant, :glutenfree, :vegan, :image, :title)
end
3: run rails s

Couldn't find User with 'id'=

I've honestly looked everywhere for a fix to this error, People have had similar problems but I can't find any that help me fix mine. I am trying to view another users profile page while being signed in as a different user. No Device, for this. I keep running into the same error that looks exactly like this.
This is my users_controller.rb,
class UsersController < ApplicationController
before_action :set_user, only: [:show, :edit, :update, :destroy]
after_action :signed_in_after_register, only: :create
def index
#users = User.all
#user = User.find(session[:user_id])
end
def dashboard
#user = User.find(session[:user_id]) unless session[:user_id] == ""
redirect_to login_path, notice: "You're not logged in" unless #user
#posts = #user.posts.order("created_at DESC").limit(3)
#comment = Comment.new
#post = Post.new
end
def newsfeed
#user = User.find(session[:user_id]) unless session[:user_id] == nil
redirect_to login_path, notice: "You're not logged in" unless #user
#posts = #user.posts.order("created_at DESC").limit(3)
end
def nav
#user = User.find(session[:user_id])
end
def posts
#user = User.find(session[:user_id])
#posts = #user.posts
end
def destroy
#user = User.find(session[:user_id]) unless session[:user_id] == ""
redirect_to login_path, notice: "You're not logged in" unless #user
end
def welcome
#user = User.find(params[:user_id]) unless session[:user_id] == ""
redirect_to login_path, notice: "You're not logged in" unless #user
end
def show
#user = User.find(params[:user_id]) unless session[:user_id] == ""
redirect_to login_path, notice: "You're not logged in" unless #user
#posts = #user.posts.order("created_at DESC").limit(3)
#comment = Comment.new
#post = Post.new
end
def new
#user = User.new
#post = Post.new(params[:post_id])
end
def edit
end
def create
#user = User.new(user_params)
respond_to do |format|
if #user.save
format.html { redirect_to dashboard_path, notice: 'User was successfully created!' }
format.json { render :profile, status: :created, location: #user }
else
format.html { render :new }
format.json { render json: #user.errors, status: :unprocessable_entity }
end
end
end
def update
respond_to do |format|
if #user.update(user_params)
format.html { redirect_to dashboard_path, notice: 'User was successfully updated.' }
format.json { render :profile, status: :ok, location: #user }
else
format.html { render :edit }
format.json { render json: #user.errors, status: :unprocessable_entity }
end
end
end
def destroy
#user.destroy
respond_to do |format|
format.html { redirect_to users_url, notice: 'User was successfully destroyed.' }
format.json { head :no_content }
end
end
private
def set_user
#user = User.find(params[:id])
end
def signed_in_after_register
session[:user_id] = #user.id
end
def user_params
params.require(:user).permit(:first_name, :last_name, :bio, :password, :password_confirmation, :email, :age, :profile_picture, :post, :body)
end
end
This is my user model user.rb,
class User < ActiveRecord::Base
has_secure_password
validates :first_name, :last_name, :email, presence: true, uniqueness: true
validates_inclusion_of :age, in: 10..100
validates :password, presence: true, length: { minimum: 4 }, allow_nil: true
has_many :posts
has_attached_file :profile_picture, :styles => { :medium => "300x300>", :thumb => "100x100>" },
:default_url => "app/assets/images/missing.png",
:path => ":rails_root/public/system/:class/:attachment/:id_partition/:style/:filename"
validates_attachment_content_type :profile_picture, :content_type => /\Aimage\/.*\Z/
end
This is my routes.rb,
Rails.application.routes.draw do
root 'welcome#welcome'
get 'login' => 'sessions#login', :as => :login
get 'dashboard' => 'users#dashboard', :as => :dashboard
post 'logging/user' => 'sessions#create'
get 'logout' => 'sessions#destroy', :as => :logout
get 'about' => 'about'
get 'newsfeed' => 'users#newsfeed'
resources :users, except: :show
get 'profile/:user_id' => 'users#show', as: :profile
resources :posts do
resources :comments
end
get 'index' => 'posts#index'
get 'register' => 'users#new', :as => :register
end
And I'm willing to post any code you may need to see to further help me with my problem. Any help is appreciated, I've been trying to fix this for 3 weeks now. Thank you in advanced!
Your controller is looking for "id" prior to hitting your action code, via..
before_action :set_user, only: [:show, :edit, :update, :destroy]
..which in turn is calling the "set_user" method and attempts...
User.find(params[:id])
However, your route defines the parameter as ":user_id", not ":id"...
get 'profile/:user_id' => 'users#show', as: :profile
Since you're writing your own .find query in your action, try removing ":show" from your before_action. Or alternatively you could DRY up a bit and just use ":id" everywhere to avoid confusion. :)
As I see here you are providing a field user_id in Params instead of id .you should send the id in the url itself.
ex: localhost:3000/user/12
Also inside your controller action use params[:id] instead of params[:user_id]

How to save associated id in Rails?

batchnotification_controller.rb
class BatchNotificationsController < ApplicationController
before_action :set_batch_notification, only: [:show, :edit, :update, :destroy]
respond_to :html
def index
#batch_notification = BatchNotification.new
#users = User.all
#batch_notifications = BatchNotification.all
#final_count = []
#calculated_batch_counts = CalculatedBatchCount.all.group_by{|x| x.batch.batch_number if !x.batch.nil? }
#a = CalculatedBatchCount.all.group_by{|k| k.batch.serial_id if !k.batch.nil? }
#calculated_batch_counts.each do |key, values|
count = values.map{|x| x.finalCount}.length
h = {"batch_number" => key, "batch_id" => values.map{|x| x.batch.serial_id},"finalcount" => values.map{|x| x.finalCount}.sum(:+)/count}
#final_count << h
end
puts
# => render :json => #final_count and return
respond_with(#batch_notifications)
end
def show
respond_with(#batch_notification)
end
def new
#batch_notification = BatchNotification.new
respond_with(#batch_notification)
end
def edit
end
def create
#batch_notification = BatchNotification.new(batch_notification_params)
respond_to do |format|
if #batch_notification.save
format.html { redirect_to batch_notifications_path, notice: 'batch_notification was successfully created.' }
format.json { render action: 'index', status: :created, location: #batch_notification }
format.js
else
format.js
format.html { render action: 'new' }
format.json { render json: #batch_notification.errors, status: :unprocessable_entity }
end
end
end
def update
#batch_notification.update(batch_notification_params)
respond_to do |format|
if #vehicle.update(vehicle_params)
format.html { redirect_to #batch_notification, notice: 'batch_notification was successfully updated.' }
format.json { head :no_content }
format.js
else
format.js
format.html { render action: 'edit' }
format.json { render json: #batch_notification.errors, status: :unprocessable_entity }
end
end
end
def destroy
#batch_notification.destroy
respond_with(#batch_notification)
end
private
def set_batch_notification
#batch_notification = BatchNotification.find(params[:id])
end
def batch_notification_params
params.require(:batch_notification).permit(:message,:approved,:finalCount, :batch_id, :user_id)
end
end
user_controller.rb
class UsersController < ApplicationController
before_action :set_user, only: [:show, :edit, :update, :destroy]
load_and_authorize_resource
# GET /users
# GET /users.json
def index
#users = User.all.order('created_at DESC')
end
# GET /users/1
# GET /users/1.json
def show
end
# GET /users/new
def new
#user = User.new
end
# GET /users/1/edit
def edit
end
# POST /users
# POST /users.json
def create
respond_to do |format|
if #user.save
format.html { redirect_to users_path, notice: 'User was successfully created.' }
format.json { render action: 'show', status: :created, location: #user }
format.js
else
# render :text => #user.errors.inspect and return
format.html { redirect_to users_path, notice: 'Erors while creating User'}
format.json { render json: #user.errors, status: :unprocessable_entity }
format.js
end
end
end
# PATCH/PUT /users/1
# PATCH/PUT /users/1.json
# def update
# respond_to do |format|
# if #user.update(user_params)
# format.html { redirect_to #user, notice: 'User was successfully updated.' }
# format.json { head :no_content }
# else
# format.html { render action: 'edit' }
# format.json { render json: #user.errors, status: :unprocessable_entity }
# end
# end
# end
def update
if user_params[:password].blank?
user_params.delete(:password)
user_params.delete(:password_confirmation)
end
params[:user][:name] = params[:user][:name].capitalize if !params[:user][:name].nil?
successfully_updated = if needs_password?(#user, user_params)
#user.update(user_params)
else
#user.update_without_password(user_params)
end
respond_to do |format|
if successfully_updated
format.html { redirect_to users_path, notice: 'User was successfully updated.' }
format.json { head :no_content }
else
format.html { render action: 'edit' }
format.json { render json: #user.errors, status: :unprocessable_entity }
end
end
end
# DELETE /users/1
# DELETE /users/1.json
def destroy
#user.destroy
respond_to do |format|
format.html { redirect_to users_url }
format.json { head :no_content }
format.js { render :layout => false}
end
end
private
# Use callbacks to share common setup or constraints between actions.
def set_user
#user = User.find(params[:id])
end
# Never trust parameters from the scary internet, only allow the white list through.
def user_params
params.require(:user).permit(:email, :password, :password_confirmation, :name, :role_id,:department_id,:encrypted_password, :plant_id)
end
protected
def needs_password?(user, params)
params[:password].present?
end
end
batchnotification.rb
class BatchNotification
include Mongoid::Document
include Mongoid::Timestamps
include Mongoid::Autoinc
field :finalCount, type: Float
field :message, type: String
field :approved, type: Boolean
field :batch_id, type: Integer
field :user_id, type:Integer
belongs_to :batch
belongs_to :user
belongs_to :calculated_batch_counts
end
user.rb
class User
include Mongoid::Document
include Mongoid::Timestamps
include DeviseTokenAuth::Concerns::User
# field :locked_at, type: Time
field :name, type: String
field :role_id , type: Integer
field :department_id , type: Integer
## unique oauth id
field :provider, type: String
field :uid, default: ""
belongs_to :role
belongs_to :department
belongs_to :plant
has_and_belongs_to_many :batches, :dependent => :destroy
has_many :batch_notifiations , :dependent => :destroy
end
_form.html.erb
<%= simple_form_for(#batch_notification) do |f| %>
<%= f.error_notification %>
<%= f.check_box :approved, label: false%>
<%= f.input :message, label: false, placeholder:"message"%>
<%= f.submit "Add", class: "btn btn-primary" %>
<% end %>
I have two models with belongs to, has_many associations. Here not saving User_id in Batchnotification model please tell me the detailed procedure to how to store user id.

1 error prohibited this user from being saved:Password can't be blank

When I do lesson6 of Rails Tutorial (by Michael Hartl),there is a problem:1 error prohibited this user from being saved:Password can't be blank.
gem 'bcrypt-ruby'
This is my User model
class User < ActiveRecord::Base
has_many :microposts
attr_accessor :name ,:email
VALID_EMAIL_REGEX = /\A[\w+\-.]+#[a-z\d\-.]+\.[a-z]+\z/i
validates :name, presence: true, length: { maximum: 50 }
validates :email, presence: true , format: { with: VALID_EMAIL_REGEX }
before_save { self.email = email.downcase }
has_secure_password
end
I've created user and now appears
Processing by UsersController#create as HTML
Parameters: {"utf8"=>"✓", "authenticity_token"=>"4TpdKJZ3BeSxpH4pWUK4L1LwzBvJmBo/4MHnYlGQsmQ=", "user"=>{"name"=>"tom", "email"=>"tom#gmail.com", "password"=>"[FILTERED]", "password_confirmation"=>"[FILTERED]"}, "commit"=>"Create User"}
Unpermitted parameters: password, password_confirmation
The User Controller
class UsersController < ApplicationController
before_action :set_user, only: [:show, :edit, :update, :destroy]
# GET /users
# GET /users.json
def index
#users = User.all
end
# GET /users/1
# GET /users/1.json
def show
end
# GET /users/new
def new
#user = User.new
end
# GET /users/1/edit
def edit
end
# POST /users
# POST /users.json
def create
#user = User.new(user_params)
respond_to do |format|
if #user.save
format.html { redirect_to #user, notice: 'User was successfully created.' }
format.json { render action: 'show', status: :created, location: #user }
else
format.html { render action: 'new' }
format.json { render json: #user.errors, status: :unprocessable_entity }
end
end
end
# PATCH/PUT /users/1
# PATCH/PUT /users/1.json
def update
respond_to do |format|
if #user.update(user_params)
format.html { redirect_to #user, notice: 'User was successfully updated.' }
format.json { head :no_content }
else
format.html { render action: 'edit' }
format.json { render json: #user.errors, status: :unprocessable_entity }
end
end
end
# DELETE /users/1
# DELETE /users/1.json
def destroy
#user.destroy
respond_to do |format|
format.html { redirect_to users_url }
format.json { head :no_content }
end
end
private
# Use callbacks to share common setup or constraints between actions.
def set_user
#user = User.find(params[:id])
end
# Never trust parameters from the scary internet, only allow the white list through.
def user_params
params.require(:user).permit(:name, :email)
end
end
How to solve this problem "Unpermitted parameters"? thanks
You need add unpermitted params to
def user_params
params.require(:user).permit(:name, :email, :password, :password_confirmation)
end
PS I think you should read about strong_parameters

Password can't be blank, Bcrypt

After installing Bcrypt on my Rails app, there is a validation problem :password=>"Can't be blank", even though form is filled out:
This is my User model
class User < ActiveRecord::Base
before_save { self.email = email.downcase }
validates :username, presence: true, length: { maximum: 50 }
VALID_EMAIL_REGEX = /\A[\w+\-.]+#[a-z\d\-.]+\.[a-z]+\z/i
validates :email, presence: true,
format: { with: VALID_EMAIL_REGEX },
uniqueness: { case_sensitive: false }
has_secure_password
validates :password, length: { minimum: 6 }
end
I've tried in the rails c and now the digest appears:
User.create:
User.create(username: "Riprova", email:"testato#gmail.com", password: "nonfunzia", password_confirmation:"nonfunzia")
<User id: 15, username: "Riprova", name: nil, surname: nil, email: "testato#gmail.com", gender: nil, birth: nil, created_at: "2013-08-11 15:35:03", updated_at: "2013-08-11 15:35:03", password_digest: "$2a$10$Q/5qtZYDXRcFsUWgve3JL.wui4hSHLhGgsuO0C6TTkBY...">
User controller:
class UsersController < ApplicationController
before_action :set_user, only: [:show, :edit, :update, :destroy]
# GET /users
# GET /users.json
def index
#users = User.all
end
# GET /users/1
# GET /users/1.json
def show
end
# GET /users/new
def new
#user = User.new
end
# GET /users/1/edit
def edit
end
# POST /users
# POST /users.json
def create
#user = User.new(user_params)
respond_to do |format|
if #user.save
format.html { redirect_to #user, notice: 'User was successfully created.' }
format.json { render action: 'show', status: :created, location: #user }
else
format.html { render action: 'new' }
format.json { render json: #user.errors, status: :unprocessable_entity }
end
end
end
# PATCH/PUT /users/1
# PATCH/PUT /users/1.json
def update
respond_to do |format|
if #user.update(user_params)
format.html { redirect_to #user, notice: 'User was successfully updated.' }
format.json { head :no_content }
else
format.html { render action: 'edit' }
format.json { render json: #user.errors, status: :unprocessable_entity }
end
end
end
# DELETE /users/1
# DELETE /users/1.json
def destroy
#user.destroy
respond_to do |format|
format.html { redirect_to users_url }
format.json { head :no_content }
end
end
private
# Use callbacks to share common setup or constraints between actions.
def set_user
#user = User.find(params[:id])
end
# Never trust parameters from the scary internet, only allow the white list through.
def user_params
params.require(:user).permit(:username, :name, :surname, :email, :bids_left, :bids_left_free, :gender, :birth)
end
end
If you're using Rails 3.x you need to add attr_accessible :password or that parameter will be disallowed. On Rails 4, see strong parameters. The password param is probably being filtered out. Others (like username) probably as well.

Resources