It's my first attempt at Resque and doing background jobs, and I'm kind of stuck.
I have two issues at hand.
It gives me the error
undefined local variable or method `current_user'
I am not sure if what I am pushing to the worker is indeed the most correct thing.
Here is my code:
schedules_controller.rb
def trial
#schedule = current_user.schedules.new
if #schedule.save
user = User.find(params[:id])
#client = Buffer::Client.new(user.token)
Resque.enqueue(ScheduleTweets, #client)
#schedule.update_attribute(:trial, true)
flash[:notice] = "success"
redirect_to :back
else
flash[:alert] = "Try again."
redirect_to :back
end
end
and the worker:
apps/workers/schedule_tweets.rb
class ScheduleTweets
#queue = :schedules_queue
def self.perform(client)
user = User.find(params[:id])
client = Buffer::Client.new(user.token)
#list = List.first(6)
#profiles = client.profiles
#profile_ids = profiles.map(&:id)
#list.each do |list|
client.create_update(body: {text: "#{list.text}", profile_ids: #profile_ids })
end
end
end
end
my thought process is that the client is the core of the entire process and should thus be the one. However #profile_ids also contains anywhere from 1-5 values.
When I run the task I get the undefined local variable or method 'current_user'. How do I fix that, also am I doing it right by choosing the #client as the thing to add?
Try this
schedules_controller.rb
def trial
#schedule = current_user.schedules.new
if #schedule.save
user = User.find(params[:id])
#client = Buffer::Client.new(user.token)
Resque.enqueue(ScheduleTweets, user.id)
#schedule.update_attribute(:trial, true)
flash[:notice] = "success"
redirect_to :back
else
flash[:alert] = "Try again."
redirect_to :back
end
end
and the worker:
apps/workers/schedule_tweets.rb
class ScheduleTweets
#queue = :schedules_queue
def self.perform(user_id)
user = User.find(user_id)
client = Buffer::Client.new(user.token)
#list = List.first(6)
#profiles = client.profiles
#profile_ids = #profiles.map(&:id)
#list.each do |list|
client.create_update(body: {text: "#{list.text}", profile_ids: #profile_ids })
end
end
end
Related
Say "i want to save my data in database but one error is occur in both controller.
This is my Controller Code.....
class ChiefexecutiveofficerController < ApplicationController
def new
end
def index
#chiefexecutiveofficer = Chiefexecutiveofficer.all
end
def create
#chiefexecutiveofficer = Chiefexecutiveofficer.new()
#chiefexecutiveofficer.ceo_name = params[:chiefexecutiveofficer][:ceo_name]
#chiefexecutiveofficer.ceo_pin = params[:chiefexecutiveofficer][:ceo_pin]
#chiefexecutiveofficer.ceo_address = params[:chiefexecutiveofficer][:ceo_address]
#chiefexecutiveofficer.ceo_salary = params[:chiefexecutiveofficer][:ceo_salary]
if #chiefexecutiveofficer.save
flash[:notice]= " Your CEO Record Is Successfully Created"
redirect_to welcome_index_path
else
flash[:notice]= " Your CEO record Is Not Created"
redirect_to welcome_index_path
end
end
private
def my_params
params.require(:chiefexecutiveofficer).permit(:ceo_name,:ceo_name,:ceo_address,:ceo_salary)
end
end
models/collaborators.rb:
class Collaborator < ActiveRecord::Base
belongs_to :user
belongs_to :wiki
def wiki_collaborations
end
end
controllers/wikis_controller.rb:
class WikisController < ApplicationController
def index
#user = current_user
if #user.admin?
#wikis = Wiki.all
elsif #user.premium?
#wikis = Wiki.where(private: false) | #user.wiki_collaborations | #user.wikis
elsif #user.standard?
#wikis = Wiki.where(private: false) | #user.wiki_collaborations
else
#wikis = Wiki.where(private: false)
end
end
def show
#wiki = Wiki.find(params[:id])
authorize #wiki
end
def new
#wiki = Wiki.new
end
def create
#wiki = current_user.wikis.new(wiki_params)
if #wiki.save
flash[:notice] = "Wiki was saved."
redirect_to #wiki
else
flash.now[:alert] = "There was an error saving the wiki. Please try again."
render :new
end
end
def edit
#user = current_user
#wiki = Wiki.find(params[:id])
#user_emails = User.where.not(id: current_user.id || #wiki.users.pluck(:id)).map(&:email)
authorize #wiki
end
def update
#wiki = Wiki.find(params[:id])
authorize #wiki
if #wiki.update(wiki_params)
flash[:notice] = "Wiki was updated."
redirect_to #wiki
else
flash.now[:alert] = "There was an error saving the wiki page. Please try again."
render :edit
end
end
def destroy
#wiki = Wiki.find(params[:id])
if #wiki.destroy
flash[:notice] = "\"#{#wiki.title}\" was deleted successfully."
redirect_to wikis_path
else
flash.now[:alert] = "There was an error deleting the wiki page."
render :show
end
end
private
def wiki_params
params.require(:wiki).permit(:title, :body, :private)
end
end
I tried to access http://localhost:3000/wikis.
I get the following error.
Possibly you've not defined wiki_collaborations method for user.
You can delegate it to User like,
class User < ActiveRecord::Base
delegate :wiki_collaborations, to: :collaborator
end
Btw, be aware of | is not same as ||.
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 :)
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.
i have two actions in my controller
def up_vote
lesson = Lesson.find(params[:id])
current_user.up_vote!(lesson)
flash[:message] = 'Thanks for voting!'
redirect_to lesson_path(lesson)
end
def down_vote
lesson = Lesson.find(params[:id])
current_user.down_vote!(lesson)
flash[:message] = 'Thanks for voting!'
redirect_to lesson_path(lesson)
end
i was wondering what would be a good way to refactor this (keeping DRY in mind)? i read online that i shouldn't be trying to abuse the before_filter. what else could i use then? thanks!
def vote_up
vote(:up)
end
def vote_down
vote(:down)
end
protected
def vote(direction)
lesson = Lesson.find(params[:id])
current_user.send :"#{direction}_vote!",lesson
flash[:message] = 'Thanks for voting!'
redirect_to lesson_path(lesson)
end
Well most obviously would be to use a single method which takes an up_or_down parameter.
def vote(up_or_down)
lesson = Lesson.find(params[:id])
if up_or_down.eql? "up"
current_user.up_vote!(lesson)
elsif up_or_down.eql? "down"
current_user.down_vote!(lesson)
else
# send an error message or just return
end
flash[:message] = 'Thanks for voting!'
redirect_to lesson_path(lesson)
end