Getting error "Can't convert FixNum into Array" - ruby-on-rails-3

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.

Related

Using Twilio in Rails 4 - Uninitialized Constant Error

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

Destroy Record if Dependant record is not found

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

Rails: How to create an item on database using params with other data

I will try to be as simple as possible:
I have a form that gets products information (name, desc,... etc) that I would like to add to the Store products list (using model association: product belongs_to :store and store has_many :products).
In addition to that information, I would like to add a 'ON' status field to product table. Why? In the case the product owner would like to delete the product, the status goes to 'OFF' instead of destroying completely the product on database (for stats reasons, I have to keep data for 6 months.)
Here is my controller code:
# Create a new product for the actual company.
def create
# Get store information.
#store = Store.find_by_id session[:store_id]
# Set new store product.
product = #store.products.build(
:name => params[:product][:name],
:desc => params[:product][:desc],
:url => params[:product][:url],
:status => 'ON'
)
if product.save
redirect_to :back, :notice => 'Product successfully created.'
else
redirect_to :back, :alert => 'Something goes wrong.'
end
end
I tried this shortcut, but it doesn't work:
product = #store.products.build(params, :status => 'ON')
My question, is how to add :status => 'ON' more elegantly than listing all params?
Thanks in advance.
product = #store.products.build(params[:product])
product.status = 'ON'
I think you can create a scope, say scope :enabled, conditions: {status: 'ON'}, and then you can do product = #store.products.enabled.build(params[:product]).

No MethodError when trying get active record id

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.

Rails 3 - Request Params turn into Scope calls

I'm building an application that has a bunch of Monthly Total reports. Most of them are very similar and they are all working now but the code sucks. I have to clean this up and trying to figure out the best approach in doing so.
def active_monthly_total_by_type
respond_to do |format|
format.html
format.json {
#results = #current_account.items.totals_by_month(params[:selected_year], :status_change_date).with_type.active
render :json => #results.collect{ |result| { :type => result.type, :jan => result.jan, :feb => result.feb, :mar => result.mar, :apr => result.apr, :may => result.may, :jun => result.jun, :jul => result.jul, :aug => result.aug, :sep => result.sep, :oct => result.oct, :nov => result.nov, :dec => result.dec } }
}
end
end
def active_monthly_total
respond_to do |format|
format.html
format.json {
#results = #current_account.items.totals_by_month(params[:selected_year], :status_change_date).active
render :json => #results.collect{ |result| { :jan => result.jan, :feb => result.feb, :mar => result.mar, :apr => result.apr, :may => result.may, :jun => result.jun, :jul => result.jul, :aug => result.aug, :sep => result.sep, :oct => result.oct, :nov => result.nov, :dec => result.dec } }
}
I have 6 total methods like this and I'm trying to figure out if I pass it a param of active or inactive
params[:active]
if I can attach it to this call
#results = #current_account.items.totals_by_month(params[:selected_year], :status_change_date).params[:active]
if anyone can help or give me some advise where I can look for information I would love to have one method that controls all of these calls since they are the same. Here is the model scope:
def self.totals_by_month(year, date_type)
start_date = year.blank? ? Date.today.beginning_of_year : Date.parse("#{year}0101").beginning_of_year
end_date = year.blank? ? Date.today.end_of_year : Date.parse("#{year}0101").end_of_year
composed_scope = self.scoped
start_date.month.upto(end_date.month) do |month|
composed_scope = composed_scope.select("COUNT(CASE WHEN items.#{date_type.to_s} BETWEEN '#{start_date.beginning_of_month}' AND '#{start_date.end_of_month}' THEN 1 END) AS #{Date::ABBR_MONTHNAMES[month].downcase}")
start_date = start_date.next_month
end
composed_scope
end
I found a unique way to do this. I created a method called pie_chart and bar_chart which handles HTML and JSON for the requests and implemented this structure
/reports/:method/:year/:name/
send(params[:method],#current_account.items.send(params[:scope], params[:year]))
Where the URL would be /reports/pie_chart/2010/count_types_by_year
I have a pie_chart method in my controller and a count_types_by_year as the scope in my model and works like a charm Completely makes it dynamic and also makes it flexible for new additions...DRY baby DRY