I am tring to write a script that checks to see if the corresponding record exist. if not i want to delete the record of reference.
I am new to ruby.
if Hotload.find(lead.id).exists?
leadid = Lead.find(lead.id)
leadid.destroy
end
error message:
ActiveRecord::RecordNotFound (Couldn't find Hotload with id=148):
app/controllers/users_controller.rb:64:in `block in leads'
app/controllers/users_controller.rb:47:in `leads'
UPDATE:
Here is complete Function:
def leads
load_leads = []
truck_leads = []
hotload_leads = []
#I just added another route for users/:id/leads and kept users/leads because I wasn't sure if it was used anywhere else.
#leads = Lead.where(:user_id => params[:id] || current_user.id)
#leads.each do |lead|
if lead.post_type == 'load'
load_leads.push lead.type_id
elsif lead.post_type == 'truck'
truck_leads.push lead.type_id
elsif lead.post_type == 'hotload'
hotload_leads.push lead.type_id
unless Hotload.where(:id => lead.id).exists?
lead_id = Lead.find(lead.id)
lead_id.destroy
end
end
end
#saved_loads = Load.find(load_leads, :order => "#{sort_load_column + " " + sort_direction}").paginate(:page => params[:load_leads_page], :per_page => 10)
#saved_trucks = Truck.find(truck_leads,:order => "#{sort_truck_column + " " + sort_direction}").paginate(:page => params[:truck_leads_page], :per_page => 10)
#saved_hotloads = Hotload.find(hotload_leads,:order => "#{sort_load_column + " " + sort_direction}").paginate(:page => params[:hotload_leads_page], :per_page => 10)
end
Error Now
ActiveRecord::RecordNotFound (Couldn't find all Hotloads with IDs (1590, 1479, 1478, 1468, 1476) (found 4 results, but was looking for 5)):
app/controllers/users_controller.rb:62:in `leads'
You should change the code to
if Hotload.find_by(id: lead.id).blank?
leadid = Lead.find(lead.id)
leadid.destroy
end
If you look at the documentation for find, you'll see that it will raise an error if one or more ids cannot be found.
Try using where instead.
if Hotload.where(:id => lead.id).exists?
lead_id = Lead.find(lead.id)
lead_id.destroy
end
Related
I am trying to integrate Twilio with my Rails 4 app. I followed a tutorial, but I keep getting an error. Right now I am getting an Uninitialized Constant Error. I provided the code below. Thanks in advance.
Routes.rb
get '/share_over_sms' => 'listing_collections#share_over_sms'
Listing Collection Model
require "messenger"
def clean_number
client_number = self.client_number.scan(/\d+/).join
client_number[0] == "1" ? client_number[0] = '' : client_number
client_number unless client_number.length != 10
end
Messenger Module
module Messenger
def send_sms(number)
twilio_sid = "ENV['TWILIO_ACCOUNT_SID']"
twilio_token = "ENV['TWILIO_AUTH_TOKEN']"
#twilio_client = Twilio::REST::Client.new twilio_sid, twilio_token
from = '+1xxxxxxxxxx'
message = #twilio_client.account.sms.messages.create(
:from => from,
:to => "+1"+number,
:body => "This is a test message."
)
end
end
Listing Collections Controller
def share_over_sms
#client_phone = ClientPhone.new(listing_collection_params)
#client_phone.send_sms(#client_phone.clean_number)
redirect_to :back
end
class CartItemsController < ApplicationController
before_filter :initialize_cart, :check_not_signedin
def create
product = Product.find(params[:product_id])
kart = initialize_cart
qty = CartItem.select(:quantity).where(:cart_id => kart.id, :product_id => product.id)
if qty == 0
#item = CartItem.new(:cart_id => kart.id, :product_id => product.id, :quantity => qty+1)
if #item.save
flash[:success] = "Product added"
redirect_to category_products_path
end
else
if CartItem.where("cart_id = ? AND product_id = ?", kart.id, product.id).first.update_column(:quantity, qty+1)
flash[:success] = "Product updated"
redirect_to category_products_path
end
end
end
When I am trying to run this I'm getting the following error
"Can't convert FixNum into Array"
app/controllers/cart_items_controller.rb:17:in `create'
Please help!
The following line should return a ActiveRecord::Relation into qty:
qty = CartItem.select(:quantity).where(:cart_id => kart.id, :product_id => product.id)
You should use qty.count instead: qty.count == 0
Also, you can't add a ActiveRecord::Relation with 1 like this: qty+1. It will give you the error message you had.
I'm not sure what you are trying to do, but I suggest you use the debugger gem to help you troubleshoot your problem. Follow the guide here to setup, it's very simple to setup: http://guides.rubyonrails.org/debugging_rails_applications.html#debugging-with-the-debugger-gem
Then, place debugger in your code:
product = Product.find(params[:product_id])
kart = initialize_cart
qty = CartItem.select(:quantity).where(:cart_id => kart.id, :product_id => product.id)
debugger # <---- here
if qty == 0
#item = CartItem.new(:cart_id => kart.id, :product_id => product.id, :quantity => qty+1)
if #item.save
Then you can find out more while you stopped at the debugger breakpoint, you can do stuff like:
qty.class
qty.count
# etc
Also, you can run rails console for testing.
I'm guessing that the following line is returning an Array:
CartItem.select(:quantity).where(:cart_id => kart.id, :product_id => product.id)
If this is the case then you can't simply add +1 to it on this line:
if CartItem.where("cart_id = ? AND product_id = ?", kart.id, product.id).first.update_column(:quantity, qty+1)
If this is not the case, can you point out which line is number 17 as pointed out in the error message.
Using rails 3, How could one do multiple where statements without complicated stuff or extra gems?
Im having this column "accepted" and would like to get all the values where accepted == false and accepted == null
Both of examples below fail:
#scholars = Scholars.where(:scholar_id => current_user.id).where(["accepted = ? or accepted = ?", true, null])
and
#scholars = Scholars.where(:scholar_id => current_user.id).where(:accpeted => true).where(:accepted=> null)
Try:
#scholars = Scholars.where(:scholar => current_user, :accepted => true).all +
Scholar.where(:scholar => current_user, :accepted => nil).all
Did you name your model "Scholars"? Models are traditionally singular... if you named it properly, this should be Scholar.where(...).
The correct answer should be
#profiles = Profile.where(:user_id => current_user.id, :accepted => [true, nil]).order(:accepted)
I am new to rails and have just started writing tests using rspec version : 2.11.1 . I am looking for a way to seed different data for different tests in my class. For this I created a static function in the test itself. Depending on the requirements I am in instantiating different number of objects. I have a function seed_data which instantiates different number of objects based on the number passed to it. I get this exception :
NoMethodError: undefined method `seed_data' for #<RSpec::Core::ExampleGroup::Nested_1::Nested_5::Nested_1:0x007fcedd9bea70>
Please have a look at the sample code below :
require 'spec_helper'
require 'go_live_sale'
require 'rspec/expectations'
describe GoLiveSale do
context "get_go_live_sale_for_sale_ids Function Correctness" do
describe "Testing get_go_live_sale_for_sale_ids() function correctness " do
it "should return error when sale_ids is blank" do
result = GoLiveSale.get_go_live_sale_for_sale_ids({})
result[:err].should_not be_blank
result[:err].should == "err1"
end
it "should return all columns corresponding to select field for single go_live_sale" do
go_live_sales = seed_data(1)
sale_ids = go_live_sales.map{ |go_live_sale| go_live_sale.sale_id}
result = GoLiveSale.get_go_live_sale_for_sale_ids({:sale_ids => sale_ids})
result[:err].should be_blank
result[:go_live_sales].count.should_be == 1
delete_seed_data(go_live_sales)
end
it "should return all columns corresponding to select field for multiple go_live_sale" do
go_live_sales = seed_data(2)
sale_ids = go_live_sales.map{ |go_live_sale| go_live_sale.sale_id}
GoLiveSale.get_go_live_sale_for_sale_ids({:sale_ids => sale_ids})
result[:err].should be_blank
result[:message].should be_blank
result[:go_live_sales].count.should == 2
delete_seed_data(go_live_sales)
end
it "should return selected columns corresponding to select field for single go_live_sale" do
go_live_sales = seed_data(1)
sale_ids = go_live_sales.map{ |go_live_sale| go_live_sale.sale_id}
result = GoLiveSale.get_go_live_sale_for_sale_ids({:sale_ids => sale_ids, :columns => ["id","sale_id"]})
result[:err].should be_blank
result[:go_live_sales].count.should_be == 1
delete_seed_data(go_live_sales)
end
it "should return selected columns corresponding to select field for multiple go_live_sale" do
go_live_sales = seed_data(2)
sale_ids = go_live_sales.map{ |go_live_sale| go_live_sale.sale_id}
GoLiveSale.get_go_live_sale_for_sale_ids({:sale_ids => sale_ids, :columns => ["id","sale_id"]})
result[:err].should be_blank
result[:message].should be_blank
result[:go_live_sales].count.should == 2
delete_seed_data(go_live_sales)
end
it "should return error when selecting erroneous columns" do
go_live_sales = seed_data(2)
sale_ids = go_live_sales.map{ |go_live_sale| go_live_sale.sale_id}
GoLiveSale.get_go_live_sale_for_sale_ids({:sale_ids => sale_ids, :columns => ["id","random_sale_id"]})
result[:err].should_not be_blank
delete_seed_data(go_live_sales)
end
end
end
end
def self.delete_seed_data(go_live_sales)
go_live_sales.each do |go_live_sale|
go_live_sale.delete
end
end
def self.seed_data(number_of_go_live_sale_to_create)
go_live_sales =[]
(1..number_of_go_live_sale_to_create).each do |number|
go_live_sales.push(create_go_live_sale(number))
end
return go_live_sales
end
def self.create_go_live_sale(number_to_add)
go_live_sale = GoLiveSale.new
go_live_sale.start_date = Time.now
go_live_sale.sale_id = Sale.select("IFNULL(max(id),0)+#{number_to_add} as sale_id").first.try(:sale_id)
go_live_sale.sale_name = "Test Sale" + go_live_sale.sale_id.to_s
go_live_sale.sale_type = "Flash Sale"+ go_live_sale.sale_id.to_s
User.current_user = User.first
go_live_sale.save
return go_live_sale
end
RSpec::Matchers.define :be_valid do
match_for_should do |actual|
actual[:err].blank?
actual[:validation_error].blank?
actual[:is_valid] == true
end
match_for_should_not do |actual|
actual[:err].present?
actual[:validation_error].present?
actual[:is_valid] == false
end
failure_message_for_should do |actual|
"Expected validation to pass, but it failed"
end
failure_message_for_should_not do |actual|
"Expected validation to fail, but it passed"
end
end
I understand that it is some scope issue or maybe rspec doesn't let you write the tests that way. It will be great if some one can write a small snippet of code explaining how to instantiate test data in such cases. My rails version is 3.0.5.
You can just get rid of the self. in the method definition and move it inside the describe GoLiveSale do block, then call it with seed_data as expected.
For example:
describe GoLiveSale do
def my_method
end
context "some context" do
it "should call my_method" do
expect {my_method}.not_to raise_error
end
end
end
This spec should pass.
In model:
def self.get_by_slug(slug)
self.where("slug = ?", slug)
end
In controller:
#route: match '/category/:slug', :to => 'category#index', :as => "category_jobs"
#category = Category.get_by_slug(params[:slug])
#jobs = Job.where("category_id = ? AND expires_at > ?", #category.id, DateTime.now)
.paginate(:page => params[:page], :per_page => Jobeet::Application::MAX_JOBS_ON_CATEGORY_PAGE)
.order("expires_at desc")
When I trying get category.id in controller I am getting error:
undefined method `id' for #
Could somebody give me any advice?
If you expect a single record you should do:
#category = Category.get_by_slug(params[:slug]).first
because .where(something) doesn't return a single record.