Ruby On Rails 6, gender validation - ruby-on-rails

I am trying to set the gender validation depending on the penultimate digit of the PESEL number (if the digit is even, then the gender is 'female'). For now my Profile.rb look like that:
class Profile < ApplicationRecord
enum gender: %i[male female]
validates :first_name, presence: true, on: :update
validates :last_name, presence: true, on: :update
validates :gender, presence: true, on: :update
validates :pesel, presence: true, on: :update
validates :contact_number, presence: true, on: :update
validates :pesel, format: { with: /\A(\d{11})\z/ }, on: :update
validate :gender_correct?
def gender_correct?
return self.pesel.blank?
if self.pesel[-2].to_i % 2 != 0
pesel_gender = 'male'
else
pesel_gender = 'female'
end
if pesel_gender != self.gender
errors.add(:gender, t('activerecord.errors.models.profile.attributes.gender.wrong'))
end
end
Unfortunately it doesn't work. Other validations works fine.
EDIT:
My update action:
def update
#profile = Profile.find(params[:id])
respond_to do |format|
#profile.avatar.attach(params[:avatar]) if params[:avatar].present?
if #profile.errors.empty? && #profile.update(profile_params)
#profile.onboarded = true
#profile.save
#profile.fill_info!
#profile.assign_dispensary
format.html { redirect_to authenticated_root_path, notice: t('.update.success') }
format.json { render :show, status: :ok, location: #profile }
else
format.html { render 'pages/info', alert: t('.update.error') }
format.json { render json: #profile.errors, status: :unprocessable_entity }
end
end
end
If i tried to update profile with blank first/last name, pesel, gender or contact number,then an error is displayed below text field.
Before update:
https://drive.google.com/file/d/1uS30WKLBFt5jcUUycI4CQblnEOpkrWEc/view?usp=sharing
After update:
https://drive.google.com/file/d/1HJqk-0opJdoZQ37CkPwscfL8Ohb19n6A/view?usp=sharing
I wanted to display error "PESEL does not match the set gender. Correct the PESEL number." under gender text field if PESEL gender doesn't match selected gender. Is that enough info? Or should I add something else?

Related

undefined method `save' for nil:NilClass for my app

[enter image description here][1]
I keep getting this error message and can not figure out why it is. I believe it is because #resturant is nil. But I do not understand why it is nil.
Is there anyway to 'print or console log' the response so I can see what the problem is
[1]: https://i.stack.imgur.com/sHUrz.png
Here is the model
class Resturant < ApplicationRecord
mount_uploader :image, ImageUploader
serialize :image, JSON # If you use SQLite, add this line
belongs_to :user, optional: true
validates :name, :description, :location, :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 the controller:
class Resturant < ApplicationRecord
mount_uploader :image, ImageUploader
serialize :image, JSON # If you use SQLite, add this line
belongs_to :user, optional: true
validates :name, :description, :location, :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
# GET /resturants/new
def new
#resturant = Resturant.new
end
# GET /resturants/1/edit
def edit
end
# POST /resturants or /resturants.json
def create
#resturants = Resturant.new(resturant_params)
respond_to do |format|
if #resturant.save
format.html { redirect_to resturant_url(#resturant), notice: "Resturant was successfully created." }
format.json { render :show, status: :created, location: #resturant }
else
format.html { render :new, status: :unprocessable_entity }
format.json { render json: #resturant.errors, status: :unprocessable_entity }
end
end
end
# PATCH/PUT /resturants/1 or /resturants/1.json
def update
respond_to do |format|
if #resturant.update(resturant_params)
format.html { redirect_to resturant_url(#resturant), notice: "Resturant was successfully updated." }
format.json { render :show, status: :ok, location: #resturant }
else
format.html { render :edit, status: :unprocessable_entity }
format.json { render json: #resturant.errors, status: :unprocessable_entity }
end
end
end
# DELETE /resturants/1 or /resturants/1.json
def destroy
#resturant.destroy
respond_to do |format|
format.html { redirect_to resturants_url, notice: "Resturant was successfully destroyed." }
format.json { head :no_content }
end
end
private
# Use callbacks to share common setup or constraints between actions.
def set_resturant
#resturant = Resturant.find(params[:id])
end
# Only allow a list of trusted parameters through.
def resturant_params
params.require(:resturant).permit(:name, :genre, :description, :location, :glutenfree, :vegan, :image, :resturant)
end
end
You have a typo. (It often takes a second set of fresh eyes to see these.)
You have accidentally pluralized resturant in your create action but then are using the singular later on.
You have:
#resturants = Resturant.new(resturant_params)
Change it to:
#resturant = Resturant.new(resturant_params)
(You are also misspelling "Restaurant" throughout your entire application. It is up to you if you'd like to fix that or not. I know I myself have trouble spelling that one for some silly reason.)

if user.save not working in respond_to do |format| when fails validations

In my case it is pre_member instead of user. Even when it fails validations (pre_member does not save), it remains within the if block, does not go the the else block.
validations
class PreClubList < ActiveRecord::Base
validates_presence_of :email, :enterprise, :member
VALID_EMAIL_REGEX = /\A[\w+\-.]+#[a-z\d\-]+(\.[a-z]+)*\.[a-z]+\z/i
validates :email, format: { with: VALID_EMAIL_REGEX }
validates :enterprise, length: { minimum: 3 }
end
So if a user puts in one character for enterprise it still follows what's in the if block but doesn't save it.
action
class PreClubListsController < ApplicationController
def create
#member = PreClubList.new(pre_club_list_params)
respond_to do |format|
if #member.save
format.html
format.js { render "create" }
else
format.html
format.js {"alert('form had following errors : #{#member.errors.full_messages});"}
end
end
end
private
def pre_club_list_params
params.require(:pre_club_list).permit(:email, :enterprise, :member)
end
end
I'm using rails 4.1, simple_form

Rails - Form not passing validations

I have these validation rules:
class Employee < ActiveRecord::Base
validates :name, 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 }
before_save { self.email = email.downcase }
end
Here is debug(params)
--- !ruby/hash:ActionController::Parameters
utf8: ✓
authenticity_token: rqWNFu2/jeoZfTTZD5N6M080UcazPZR2hl0ON92sxnA=
employee: !ruby/hash:ActionController::Parameters
name: xxx
email: yyyy#zzzz.com
password: '123456'
password_confirmation: '123456'
commit: Create Employee
action: create
controller: employees
But the validation still fails saying:
Email can't be blank
Email is invalid
Password can't be blank
Password is too short (minimum is 6 characters)
edit: controller code
def create
#employee = Employee.new(employee_params)
respond_to do |format|
if #employee.save
format.html { redirect_to #employee, notice: 'Employee was successfully created.' }
format.json { render action: 'show', status: :created, location: #employee }
else
format.html { render action: 'new' }
format.json { render json: #employee.errors, status: :unprocessable_entity }
end
end
end
Anyone can explain to me what i am doing wrong? The params seems to be fine and filled correctly but i still can't pass the validation
The problem is caused by incorrect use of Strong Parameters. Declaring employee_params the following way should fix it:
private
def employee_params
params.require(:employee).permit(:name, :email, :password, :password_confirmation)
end
With Rails4 Strong Parameters concept, you must permit the parameters that you would like to insert(create action)/update(update action) in database explicitly else they won't pass through.
Permit email and password in employee_params method.
employee_params should look as below:
def employee_params
params.require(:employee).permit(:email, :password, :password_confirmation, :name)
end

Access Param in model

I know this is something you can't do inside of rails or aren't supposed to do but I need to somehow get the amount a user is inputing in a field of the form and use that value.
This is what my model looks like
class Deposit < ActiveRecord::Base
belongs_to :credit_card
belongs_to :user
validates :credit_card, presence: true
validates :user, presence: true
validates :tx_type, inclusion: %w(debit credit)
# validates :amount, presence: true, numericality: true
before_create :add_transaction_to_merchant
after_create :update_user_balance
attr_readonly :credit_card_id, :user_id, :fee_id, :tx_type, :status, :merchant_tx_id
attr_accessible :tx_type, :amount, :status, :merchant_tx_id, :credit_card_id,
:user_id, :user
def amount
return attributes[:amount] if attributes[:amount]
set_amount
end
def tx_type
attributes[:tx_type] || 'debit'
end
def send_receipt
Resque.enqueue(PaymentCompletedSender, self.id)
end
def update_user_balance
user_balance =user.balance + set_amount
user.balance = user_balance
user.save
end
private
def add_transaction_to_merchant
set_amount
return false if credit_card.nil?
return true unless amount > 0
result = Braintree::Transaction.sale(
amount: amount,
payment_method_token: credit_card.token,
options: { submit_for_settlement: true }
)
if result.success?
self.merchant_tx_id = result.transaction.id
# status will be authorized or submitted_for_settlement
self.status = result.transaction.status
else
errors.add(:base, result.message)
if result.transaction.nil?
# validation errors prevented transaction from being created
logger.error(result.errors)
else
self.merchant_tx_id = result.transaction.id
# status will be processor_declined, gateway_rejected, or failed
self.status = result.transaction.status
end
end
end
def set_amount
attributes[:amount]
end
end
The Controller:
# POST /deposits
# POST /deposits.json
def create
#deposit = Deposit.new(params[:deposit])
#deposit.user = current_user
#deposit.credit_card = current_user.credit_cards.try(:first)
binding.pry
respond_to do |format|
if #deposit.save
format.html { redirect_to "/", notice: 'Deposit was successfully created.' }
format.json { render json: #deposit, status: :created, location: #deposit }
else
format.html { render action: "new" }
format.json { render json: #deposit.errors, status: :unprocessable_entity }
end
end
end
This is what is params the form is sending
{"utf8"=>"✓",
"authenticity_token"=>"r0M0sRr7QO9kl0IWrJSgvj45DFrC6mbbuA+ttgEaUI0=",
"deposit"=>{"amount"=>"100"},
"commit"=>"Pay Now"}
Any thoughts on how to return the value of amount from the form in the model?
you are doing this right? #deposit = Deposit.new(params[:deposit]) if you remove the amount and set_amount method in the model, you should be able to just use amount or self.amount in the model so the following should be enough
def add_transaction_to_merchant
return false if credit_card.nil?
return true unless amount > 0
result = Braintree::Transaction.sale(
amount: amount,
payment_method_token: credit_card.token,
options: { submit_for_settlement: true }
)

ActiveRecord Error

I have two model class,
class Designation < ActiveRecord::Base
attr_accessible :name
validates :name, presence: true, uniqueness: { case_sensitive: false }
has_many :employee_details
accepts_nested_attributes_for :employee_details
end
and
class EmployeeDetail < ActiveRecord::Base
belongs_to :Designation
attr_accessible :bloodGroup, :dob, :doc, :doj, :empId, :name, :panNo, :status, :Designation
end
I have generated default scaffold for EmployeeDetail. from EmployeeDetail page when i tried to create and enter integer value in designation textbox, it gives me error
ActiveRecord::AssociationTypeMismatch in EmployeeDetailsController#create
Designation(#81846160) expected, got String(#75419260).
can anyone help me to sortout this problem?
EmployeeDetailController#create:-
def create
#employee_detail = EmployeeDetail.new(params[:employee_detail])
respond_to do |format|
if #employee_detail.save
format.html { redirect_to #employee_detail, notice: 'Employee detail was successfully created.' }
format.json { render json: #employee_detail, status: :created, location: #employee_detail }
else
format.html { render action: "new" }
format.json { render json: #employee_detail.errors, status: :unprocessable_entity }
end
end
end
When you associate any model, you should use the lowercase version of the model name.
Change:
belongs_to :Designation
to:
belongs_to :designation

Resources