How can I refactor the following controller fetch action, also how to use local variable(website not #website, local because it doesn't have a view) in fetch action and start_fetching method
def fetch
#website = Website.find(params[:website_id])
retun redirect_to :back, :alert => t('crawl_counter_error') if #website.fetch_counter < 1
authorize! :update, #website, :message => t("website_authorize_error")
#website.confirmed? || #website.confirmed_key? ? start_fetching : flash[:error] = t('key_error')
redirect_to :back
end
private
def start_fetching
if #website.working_status
flash[:error] = t('crawling_in_progress_error')
else
#website.start_fetch
flash[:notice] = t('crawler_success_notice')
end
end
This might be a bit cleaner
# controller
def fetch
website.find(params[:website_id])
authorize! :update, website, :message => t("website_authorize_error")
status = website.fetch
flash[status[:type]] = t(status[:message])
redirect_to :back
end
# move to model/website.rb
def fetch
status = nil
if (fetch_counter < 1)
status = {:error, 'crawl_counter_error'}
elsif confirmed? || confirmed_key?
status = {:error, 'key_error'}
elsif working_status
status = {:error, 'crawling_in_progress_error'}
else
start_fetch
status = {:notice, 'crawler_success_notice'}
end
status
end
Related
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
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 :)
I'm trying to change the status of Dispute object:
class Dispute < ActiveRecord::Base
STATUSES = %w(open finished).freeze
STATUSES.each do |method|
define_method "#{method}?" do
status == method
end
end
def self.statuses
STATUSES
end
end
in create and update methods:
def create
Dispute.new
if params[:status] == 'Open'
dispute.status = dispute.statuses[0]
end
if dispute.save
redirect_to dispute_path(#dispute)
flash[:success] = 'Hooray'
else
flash[:error] = 'Error'
redirect_to :back
end
end
I handled the attribute inside the method, but the status did not change. Is it better to change the status in the model with callback instead of the controller?
To change the status you can simply do
def create
Dispute.new
if params[:status] == 'Open'
dispute.status = dispute.statuses.open!
end
if dispute.save
redirect_to dispute_path(#dispute)
flash[:success] = 'Hooray'
else
flash[:error] = 'Error'
redirect_to :back
end
end
you can visit http://edgeapi.rubyonrails.org/classes/ActiveRecord/Enum.html for more help on enumns.
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
I have a Question & Answer feature and I am just about finished with it. I have no idea how to do the code that would send a message to user when another user has asked them a question. For example, User A sends User B a question, a inbox message is sent to User B notifying them that they have a new question.
There's two ways I thought how to go about this.
Method #1
Inside the message it will link user to the page with the Question on it so it can be answered
Method #2
Inside the message it will include the question that was asked. User can reply to message which would submit as their answer.
Questions controller:
respond_to :js, :html
def index
#questions = Question.all
respond_with(#questions)
end
def show
#question = Question.find(params[:id])
#questions = Question.order("created_at DESC")
respond_with(#questions)
end
def new
#question = Question.new
respond_with(#question)
end
def create
#question = Question.new(params[:question])
if #question.save
redirect_to questions_path, notice: 'Your question was saved successfully. Thanks!'
else
render :new, alert: 'Sorry. There was a problem saving your question.'
end
end
end
Answers controller:
def new
#question = Question.find(params[:question_id])
end
def create
#question = Question.find(params[:question_id])
if #question.update_attributes(params[:question])
redirect_to questions_path
else
render :new
end
end
end
Messages controller:
before_filter :set_user
def index
if params[:mailbox] == "sent"
#messages = #user.sent_messages
elsif params[:mailbox] == "inbox"
#messages = #user.received_messages
#elsif params[:mailbox] == "archived"
# #messages = #user.archived_messages
end
if params[:mailbox] == "unread"
#messages = #user.unread_messages
end
end
def new
#message = Message.new
if params[:reply_to]
#reply_to = User.find_by_sender_id(params[:reply_to])
unless #reply_to.nil?
#message.recipient_id = #reply_to.sender_id
end
end
end
def create
#message = Message.new(params[:message])
#message.sender_id = #user.id
if #message.save
flash[:notice] = "Message has been sent"
redirect_to user_messages_path(current_user, :mailbox=>:inbox)
else
render :action => :new
end
end
def show
#message = Message.find(params[:id])
#message.readingmessage if #message.recipient == current_user
end
def destroy
#message = Message.find(params[:id])
#message.destroy
flash[:notice] = "Successfully deleted message."
redirect_to user_messages_path(#user, #messages)
end
def delete_multiple
if params[:delete]
params[:delete].each { |id|
#message = Message.find(id)
#message.mark_message_deleted(#message.id,#user.id) unless #message.nil?
}
flash[:notice] = "Messages deleted"
end
redirect_to user_messages_path(#user, #messages)
end
private
def set_user
#user = current_user
end
end
Message model:
attr_accessible :subject, :body, :sender_id, :recipient_id, :read_at,:sender_deleted,:recipient_deleted
validates_presence_of :subject, :message => "Please enter message title"
has_many :notifications, as: :event
scope :unread, -> {where('read_at IS NULL')}
scope :not_deleted_by_recipient, where('messages.recipient_deleted IS NULL OR messages.recipient_deleted = ?', false)
scope :not_deleted_by_sender, where('messages.sender_deleted IS NULL OR messages.sender_deleted = ?', false)
belongs_to :sender,
:class_name => 'User',
:foreign_key => 'sender_id'
belongs_to :recipient,
:class_name => 'User',
:foreign_key => 'recipient_id'
# marks a message as deleted by either the sender or the recipient, which ever the user that was passed is.
# When both sender and recipient marks it deleted, it is destroyed.
def mark_message_deleted(id,user_id)
self.sender_deleted = true if self.sender_id == user_id
self.recipient_deleted = true if self.recipient_id == user_id
(self.sender_deleted && self.recipient_deleted) ? self.destroy : self.save!
end
# Read message and if it is read by recipient then mark it is read
def readingmessage
self.read_at ||= Time.now
save
end
# Based on if a message has been read by it's recipient returns true or false.
def read?
self.read_at.nil? ? false : true
end
def self.received_by(user)
where(:recipient_id => user.id)
end
def self.not_recipient_deleted
where("recipient_deleted = ?", false)
end
def self.sent_by(user)
Message.where(:sender_id => user.id)
end
def previous(same_recipient = true)
collection = Message.where('id <> ? AND created_at > ?', self.id, self.created_at).order('created_at ASC')
collection = collection.where(recipient_id: self.recipient_id) if same_recipient
collection = collection.not_deleted_by_recipient
collection.first
end
def next(same_recipient = true)
collection = Message.where('id <> ? AND created_at < ?', self.id, self.created_at).order('created_at DESC')
collection = collection.where(recipient_id: self.recipient_id) if same_recipient
collection = collection.not_deleted_by_recipient
collection.first
end
end
private
def send_notification(message)
message.notifications.create(user: message.recipient)
end
I have solved this.
Questions Controller:
def create
#question = Question.new(params[:question])
if #question.save
#message = Message.create(:subject => "Hey you have a message from #{#question.sender_id}",
:sender_id => #question.sender_id,
:recipient_id => #question.recipient_id,
:body => #question.question)
#question.message = #message
#question.save
redirect_to questions_path, notice: 'Your question was saved successfully. Thanks!'
else
render :new, alert: 'Sorry. There was a problem saving your question.'
end
end
Every time a notification is needed, you should create it. It would go for having a Notification model that takes at least the object for which the notification was created, the user that the notification goes to and a flag whether it has been read or not.
To display the notifications, the easiest way of course is to integrate that into your layout file and do something like this:
Notification.where(:user_id => #current_user).size > 0
<%= "You have #{Notification.where(:user_id => #current_user).size} notification(s)" %>
end
And to nicen things up you can create a scope inside of the Notification object which will give you the notifications for a specific user. Of course if you want all the magic like Stackoverflow has with updating the notifications through AJAX calls, you will have to do some JavaScript lifting.