Rails 5: Old value isn't updating in database - ruby-on-rails

I'm currently trying to store an updated value in the database.
The process is the following, a user chooses to buy 3 bottles, the stock goes down by -3. The stock is set within the Wines Controller and then displayed in the reservations controller for the user
The current problem is that for each new reservation, the stock get's reset in the reservations controller, since the stock isn't updating in the wines controller.
Here lays the problem:
#reservation.in_stock = wine.in_stock - #reservation.bottle
Here is my full Reservations Controller:
class ReservationsController < ApplicationController
before_action :authenticate_user!
before_action :set_reservation, only: [:approve, :decline]
def create
wine = Wine.find(params[:wine_id])
if current_user == wine.user
flash[:alert] = "Du kannst nicht deinen eigenen Wein kaufen!"
else
start_date = Date.parse(reservation_params[:start_date])
#reservation = current_user.reservations.build(reservation_params)
#reservation.wine = wine
#reservation.price = wine.price
#reservation.in_stock = wine.in_stock - #reservation.bottle
#reservation.total = wine.price * #reservation.bottle
# #reservation.save
if #reservation.save
if wine.Reservieren?
flash[:notice] = "Anfrage versendet!"
else
#reservation.Bearbeitung!
flash[:notice] = "Eroflgreich bestellt!"
end
else
flash[:alert] = "Can't make a reservation!"
end
end
redirect_to wine
end
def your_orders
#orders = current_user.reservations.order(start_date: :asc)
end
def your_reservations
#wines = current_user.wines
redirect_to root_path unless current_user.admin == true
#count = Reservation.count(:all)
#total = Reservation.sum(:total)
end
def your_upcoming_reservations
#wines = current_user.wines
redirect_to root_path unless current_user.admin == true
end
def approve
#reservation.Versendet!
redirect_to your_reservations_path
redirect_to root_path unless current_user.admin == true
end
def decline
#reservation.Abgelehnt!
redirect_to your_reservations_path
redirect_to root_path unless current_user.admin == true
end
# Each Order Details
def order_details
#orders = current_user.reservations.order(start_date: :asc)
end
private
def set_reservation
#reservation = Reservation.find(params[:id])
end
def set_stock
#reservation.in_stock = wine.in_stock
end
def reservation_params
params.require(:reservation).permit(:start_date, :bottle, :in_stock)
end
end

Related

Couldn't find Model without an ID from application_controller.rb

I am trying to create a session for a model called Commuter by defining a helper method in application_controller.rb file. As follows.
application_controller.rb
helper_method :current_commuter
def current_commuter
#commuter ||= Commuter.find session[:cid]
end
After verifying the commuter's phone number I am trying to create a
login session.
commuters_controller.rb
def verify
#commuter = Commuter.where(phone_number: params[:phone_number]).first
if (#commuter && #commuter.authenticate_otp(params[:otp],drift:300))
#commuter.auth_active = true
if #commuter.save
#Removed from session after verified it
session[:phone_number] = nil
session[:is_verified] = nil
#signed in commuter after verified it
sign_in(:commuter, #commuter)
flash[:notice] = "Your mobile no is verified."
end
else
flash[:alert] = "You have entered wrong otp.Please check again."
end
puts "#{current_commuter.phone_number}"
redirect_to root_path
end
I put a puts to check if the current_commuter is working or not. It is when I checked on the console. Now when I added few links on a view file as follows:
app/views/bookings/outstation.html.erb
<%if current_commuter.present? %>
<li> <%= link_to "Dashboard", dashboard_commuters_path %> </li>
<li> <%= link_to "Logout", destroy_commuter_session_path, method: :delete%></li>
<%else%>
<li>
<a href="" data-toggle="modal" data-target="#signinmodal">
REGISTER | LOGIN
</a>
</li>
<%end%>
Now I am getting the following error:
ActiveRecord::RecordNotFound in BookingsController#outstation
Couldn't find Commuter without an ID
EDIT
bookings_controller.rb
class BookingsController < ApplicationController
layout 'bookings'
before_action :set_ride_later_request_from_ref_id, only:[
:select_vehicle, :update_vehicle_details,
:contact_details,:complete_booking_request]
before_action :set_ride_later_request_from_uuid_ref, only:[
:request_quotations,:quotations, :confirm_booking,
:confirmation
]
before_action :set_trip_type, only: [:outstation, :local_booking]
def new_booking
#ride_later_request = RideLaterRequest.new
#vahicle = RideLaterRequest.new
end
def create_ride_later_request
#ride_later_request = RideLaterRequest.new(permitted_attributes(RideLaterRequest))
respond_to do |format|
if #ride_later_request.save
format.html {redirect_to bookings_select_vehicle_path(ref_id: #ride_later_request.rlr_ref_code.content)}
else
format.html {render :outstation}
end
end
end
def update_vehicle_details
respond_to do |format|
if #ride_later_request.update(permitted_attributes(RideLaterRequest))
format.html {redirect_to bookings_contact_details_path(ref_id:#ride_later_request.rlr_ref_code.content)}
else
format.html {render :select_vehicle}
end
end
end
def contact_details
end
def complete_booking_request
#operation = nil
if params[:get_otp].nil? && params[:get_quotations].nil?
render json:{error:"Wrongly formed request"}, status: 422
end
if params[:get_otp]
#operation = :get_otp
if #ride_later_request.update(permitted_attributes(RideLaterRequest))
SMSSender.send_otp_message(#ride_later_request.phone_number,#ride_later_request.otp_code)
return
else
render json:{error:#ride_later_request.errors.full_messages[0]}, status: 422
end
elsif params[:get_quotations]
#operation = :get_quotations
if (params[:ride_later_request][:otp].blank? ||
!#ride_later_request.authenticate_otp(params[:ride_later_request][:otp],drift:300))
render json:{error:"OTP is wrong"}, status: 422 and return
else
#ride_later_request.user_verified = true
if !#ride_later_request.save
render json:{error:#ride_later_request.errors.full_messages.first}, status:422 and return
end
if #ride_later_request.status == 'UnderConstruction'
render json:{error:"Some fields are missing. Please try again"}, status:422 and return
end
end
end
end
def request_quotations
request_loc = [#ride_later_request.pickup_lat,#ride_later_request.pickup_lng]
#rfq_agencies = #ride_later_request.rfq_agencies.sort_by{|l|l.distance_to(request_loc)}
#ride_later_quotes = #ride_later_request.ride_later_quotes.to_a
#ride_later_quotes.sort!{|a,b| a.total_payable.to_i <=> b.total_payable.to_i}
end
def quotations
#ride_later_quotes = #ride_later_request.ride_later_quotes.to_a
#ride_later_quotes.sort!{|a,b| a.total_payable.to_i <=> b.total_payable.to_i}
if session[:trip_type] == 'HourlyPackage'
render :local_booking_quotation
else
render :outstation_booking_quotations
end
end
def confirm_booking
if #ride_later_request.status=='Unfulfilled' ||
#ride_later_request.status=='Rejected' ||
#ride_later_request.status=='Ignored'
render json:{error:'Trip request has expired. Start a new booking.'}, status:422 and return
end
if #ride_later_request.status=="Cancelled"
render json:{error:'Trip request has been cancelled. Start a new booking.'}, status:422 and return
end
if #ride_later_request.status!="QuotesReady"
render json:{error:'Trip request is in wrong state. Start a new booking.'}, status:422 and return
end
#quote = #ride_later_request.ride_later_quotes.find(params[:quote_id]) rescue nil
if #quote.blank?
render json:{error:'Quotation not linked to this trip'}, status:422 and return
end
if #quote.status != 'Submitted'
render json:{error: "Quote is in wrong state #{#quote.status}. Start a new booking"}, status:422 and return
end
#quote.status = 'Accepted'
if !#quote.save
render json:{error:#quote.errors.full_messages.first}, status:422 and return
end
RideLaterRequestHandler.commuter_accepts_quote(#quote)
end
def confirmation
#ride = #ride_later_request.ride_later_ride
#quote = #ride.ride_later_quote
end
def set_ride_later_request_from_ref_id
#ref_id = params[:ref_id]
#ride_later_request = RlrRefCode.where(content:#ref_id).first.ride_later_request rescue nil unless #ref_id.blank?
if #ride_later_request.blank?
flash[:alert] = "Something went wrong. Please create new booking request."
redirect_to bookings_new_path
end
end
def set_ride_later_request_from_uuid_ref
#uuid = params[:booking_id]
#ride_later_request = RideLaterRequest.where(uuid_ref:#uuid).first rescue nil if #uuid.present?
if #ride_later_request.blank?
flash[:alert] = "Something went wrong. Please create new booking request."
redirect_to bookings_new_path
end
end
def select_vehicle
#ride_later_request = RlrRefCode.find_by_content(params[:ref_id]).ride_later_request
end
def vehicle_type_ac
if params[:booking_summary_id].present?
#ride_later_request = RideLaterRequest.find(params[:booking_summary_id])
else
#ride_later_request = RlrRefCode.find_by_content(params[:ride_later_request][:ref_id]).ride_later_request
#ride_later_request.update(vehicle_type: params[:ride_later_request][:vehicle_type], number_of_passengers: params[:ride_later_request][:number_of_passengers])
end
end
def vehicle_type
#ride_later_request = RlrRefCode.find_by_content(params[:ref_id]).ride_later_request
end
def outstation
#ride_later_request = RideLaterRequest.new(trip_type: 'Outstation')
end
def local_booking
#ride_later_request = RideLaterRequest.new(trip_type: params[:trip_type])
end
def bangalore_innova
#ride_later_request = RideLaterRequest.new(trip_type: 'Outstation')
end
def bangalore_outstation
#ride_later_request = RideLaterRequest.new(trip_type: 'Outstation')
end
def bangalore_taxi
#ride_later_request = RideLaterRequest.new(trip_type: 'Outstation')
end
def tt_for_rent
#ride_later_request = RideLaterRequest.new(trip_type: 'Outstation')
end
def minibus_for_rent
#ride_later_request = RideLaterRequest.new(trip_type: 'Outstation')
end
# def select_vehicle_local
# end
def about_us
end
def terms_conditions
end
def privacy_policy
end
def journey_way
#ride_later_request = RideLaterRequest.create(user_params)
#ride_later_request.save
respond_to do |format|
format.html {render :select_vehicle}
end
end
def outstation_booking_quotations
#ride_later_request = RideLaterRequest.find_by(id: params[:ride_later_request])
#ref_id = params[:ref_id]
end
def select_vehicle_outstation
#ride_later_request = RlrRefCode.find_by_content(params[:ref_id]).ride_later_request
redirect_to outstation_booking_quotations_path(#ride_later_request.rlr_ref_code.content, #ride_later_request )
end
def trip_summary
#ride_later_request = RlrRefCode.find_by_content(params[:ride_later_request][:ref_id]).ride_later_request
#ride_later_request.update(vehicle_type: params[:ride_later_request][:vehicle_type], number_of_passengers: params[:ride_later_request][:number_of_passengers])
puts "Ride LATER REQUEST LOG"
puts #ride_later_request
if #ride_later_request.update(additional_instructions: params[:ride_later_request][:additional_instructions], ac: 'AC')
render :template => 'bookings/booking_summary', :locals => {:ride_later_request => #ride_later_request, :ref_id => #ride_later_request.rlr_ref_code.content, :vehicle_type => params[:ride_later_request][:vehicle_type]}
else
format.html {render :index}
end
end
def user_params
params.require(:ride_later_request).permit(:pickup_area, :pickup_city, :destination_city, :pickup_lng, :pickup_lat)
end
def set_trip_type
session[:trip_type] = params[:trip_type]
end
end
It looks to me like the error's thrown here:
def current_commuter
#commuter ||= Commuter.find session[:cid]
end
Are you calling this as a before_action?
Using find raises an error if a record's not found, so I'd suggest you're either not passing in an id in session[:cid], or what you are passing doesn't match a Commuter in your db.
You can use find_by_id to avoid throwing an error (it returns nil if the record's not found), or work around this to ensure the method's only called where it should be.
Does that help?
Edit: Based on your additional info, this could be coming from any of the finds in the bookings_controller. Same explanation as above though :)

Rails: uninitialized constant class name

I'm getting this problem:
uninitialized constant QuestionsController::Question
def index
#Question
#preguntas = Question.all
#project_id = request.original_url.split('.').last
set_current_project(#project_id)
if(#project_id.include? "http")
On my QuestionController randomly after changing nothing from my application, any idea what may be causing it? here's the complete .rb file:
class QuestionsController < ApplicationController
before_action :require_user
before_action :require_project
before_action :require_user, except: [:new, :create]
before_action :current_project, only: [:index]
def index
#preguntas = Question.all
#project_id = request.original_url.split('.').last
set_current_project(#project_id)
if(#project_id.include? "http")
#project_id = "0"
end
if(#project_id != "0")
#proyecto = Project.find(#project_id)
end
end
def show
#pregunta = Question.find(params[:id])
end
def new
#pregunta = Question.new
end
def create
#pregunta = Question.new(pregunta_params)
if #pregunta.save
redirect_to #pregunta
else
render 'new'
end
end
def edit
#pregunta = Question.find(params[:id])
end
def update
#pregunta = Question.find(params[:id])
if #pregunta.update(pregunta_params)
redirect_to #pregunta
else
render 'edit'
end
end
def destroy
#pregunta = Question.find(params[:id])
#pregunta.destroy
flash[:danger] = "Se ha borrado la pregunta"
redirect_to questions_path
end
def require_same_user
set_project
if current_user != #project.user && !#current_user.admin?
flash[:danger] = "Solo puedes editar tus artículos"
redirect_to root_path
end
end
def require_project
if current_user.projects.count <1 && !current_user.admin?
redirect_to root_path
end
end
private
def pregunta_params
params.require(:question).permit(:question, :value, :phase, :area, :input)
end
end
Ensure that the Question model is defined in a file named app/models/question.rb like this:
class Question < ApplicationRecord
# methods...
end

Rails 4: how to check if an instance has been deleted

In our Rails app, we have a CalendarsController:
class CalendarsController < ApplicationController
def create
#calendar = current_user.calendars.create(calendar_params)
current_user.add_calendar_and_role(#calendar.id, 'Owner')
if #calendar.save
current_user.total_calendar_count += 1
current_user.owned_calendar_count += 1
current_user.save
flash[:success] = "Calendar created!"
redirect_to dashboard_path
else
render 'static_pages/home'
end
end
def show
#calendar = Calendar.find(params[:id])
#posts = #calendar.posts
#post = Post.new
end
def index
end
def edit
end
def destroy
Calendar.find(params[:id]).destroy
flash[:success] = "Calendar deleted"
redirect_to dashboard_path
end
private
def calendar_params
params.require(:calendar).permit(:name)
end
end
In the create action, when a new #calendar is created, we run #calendar.save to check if the new instance has actually been created, and then perform some actions.
We would like to implement a similar process in our destroy action.
We are thinking of updating the destroy method as follows:
def destroy
#calendar = Calendar.find(params[:id])
#calendar.destroy
if #calendar.delete
flash[:success] = "Calendar deleted"
current_user.total_calendar_count -= 1
if #calendar.administrations.role == "Owner"
current_user.owned_calendar_count -= 1
end
end
redirect_to dashboard_path
end
Is the syntax of this code correct, in particular if #calendar.delete and if #calendar.administrations.role == "Owner"?
And, most importantly, would the code of this destroy action make sense?
Did you think about using the persisted? method
#calendar.destroy
unless #calendar.persisted?
... some code here ....
end
I believe it would be more like:
def destroy
#calendar = Calendar.find(params[:id])
calendar_admin_role = #calendar.administrations.role
if #calendar.destroy
flash[:success] = "Calendar deleted"
current_user.total_calendar_count -= 1
if calendar_admin_role == "Owner"
current_user.owned_calendar_count -= 1
end
end
redirect_to dashboard_path
end
But this is off the top of my head after a long day at work so could be wrong.

What do I put in my sessions controller in order to allow two models to login?

So I am having trouble in my sessions controller. I am trying to allow users to signin and businessusers to signin. They both have their own respective model and table in the database. However only users can signin. This is my sessions controller currently. What can I add to the controller to allow businessusers to also signin?
class SessionsController < ApplicationController
def new
end
def create
customer = Customer.find_by_name(params[:name])
if customer && customer.authenticate(params[:password])
session[:customer_id] = customer.id
redirect_to customer
else
flash.now[:notice] = "Invalid name/password combination."
render 'new'
end
end
def destroy
if signed_in?
session[:customer_id] = nil
else
flash[:notice] = "You need to sign in first"
end
redirect_to signin_path
end
end
class SessionsController < ApplicationController
def new
end
def create
customer = Customer.find_by_name(params[:name])
if customer.present? && customer.authenticate(params[:password])
session[:user_type] = 'Customer'
session[:customer_id] = customer.id
redirect_to customer
else
businessuser = BusinessUser.find_by_name(params[:name])
if businessuser.present? && businessuser.authenticate(params[:password])
session[:user_type] = 'Business'
session[:businessuser_id] = businessuser.id
redirect_to businessuser
else
flash.now[:notice] = "Invalid name/password combination."
render 'new'
end
end
end
def destroy
if signed_in?
session[:user_type] = nil
session[:customer_id] = nil
session[:businessuser_id] = nil
else
flash[:notice] = "You need to sign in first"
end
redirect_to signin_path
end
end

How can I prevent "not-yet-approved" Admins from accessing Admin functions in my web app?

So that multiple people can be an administrator to a business page, we've created a model called administration where people can apply to be an admin of a business and thus the status of "0" is "pending" and "1" is accepted.
How can I prevent users from editing a page where their status for i is still "0" (pending).
class Administration < ActiveRecord::Base
attr_accessible :business_id, :user_id, :status
belongs_to :user
belongs_to :business
scope :pending, where('status = ?',0).order("updated_at desc")
def self.new_by_user_business( user, business)
admin = self.new
admin.business_id = business.id
admin.user_id = user.id
admin.status = 0
admin.save!
end
end
Here is the current "edit page"
<h1>Editing business</h1>
<%= render 'form1' %>
Here is the business controller.
class BusinessesController < ApplicationController
respond_to :html, :xml, :json
before_filter :authenticate_user!, except: [:index, :show]
def index
#businesses = Business.all
respond_with(#businesses)
end
def show
#business = Business.find(params[:id])
if request.path != business_path(#business)
redirect_to #business, status: :moved_permanently
end
end
def new
#business = Business.new
3.times { #business.assets.build }
respond_with(#business)
end
def edit
#business = get_business(params[:id])
#avatar = #business.assets.count
#avatar = 3-#avatar
#avatar.times {#business.assets.build}
end
def create
#business = Business.new(params[:business])
if #business.save
redirect_to #business, notice: 'Business was successfully created.'
else
3.times { #business.assets.build }
render 'new'
end
end
def update
#business = get_business(params[:id])
if #business.update_attributes(params[:business])
flash[:notice] = "Successfully updated Business."
end
#avatar = #business.assets.count
#avatar = 3-#avatar
#avatar.times {#business.assets.build}
respond_with(#business)
end
def destroy
#business = get_business(params[:id])
#business.destroy
respond_with(#business)
end
def my_business
#business = Business.all
end
def business_tickets
#user = current_user
#business = get_business(params[:id])
#tickets = #business.tickets
#business_inbox = TicketReply.where(:email => #business.callred_email)
end
def your_business
#user = current_user
#business = get_business(params[:id])
if #business.users.map(&:id).include? current_user.id
redirect_to my_business_businesses_path, notice: 'You are already an administator of this business.'
else
#admin = Administration.new_by_user_business( #user, #business)
BusinessMailer.delay(queue: "is_your_business", priority: 20, run_at: 5.minutes.from_now).is_your_business(#user,#business)
redirect_to #business, notice: 'Thank you for claiming your business, and we will be in touch with you shortly.'
end
end
def view_message
# #business = Business.find(params[:business_id])
#ticket = Ticket.find(params[:id])
#reply = #ticket.ticket_replies
end
private
def get_business(business_id)
#business = Business.find(business_id)
end
end
You could add a before_filter to check the status. You will have to change some of the logic but this is the idea
class BusinessesController < ApplicationController
before_filter :restrict_access, :only => [:edit, :update]
private
def restrict_access
#business = get_business(params[:id])
redirect to root_path, :notice => "Not Authorized" unless current_user.status == 1
end
end

Resources