undefined method `size' for nil:NilClass - ruby-on-rails-3

Why is my code returning this error?
#articles = Article.order("id DESC").where(:visible => 1)
if #aritcles.size > 15
#articles = Article.order("id DESC").where(:visible => 1).limit(15)
end
returns:
undefined method `size' for nil:NilClass
If i run
#articles = Article.order("id DESC").where(:visible => 1)
#articles.size
It returns an integer...

If that is from your real code, then you mispelled articles to aritcles.
If that is different, please provide the real code.

if #aritcles.size > 15 should be if #articles.size > 15.
But your code is odd, it is not necessary to do that.
Just do the below is enough.
#articles = Article.order("id DESC").where(:visible => 1).limit(15)

Replace #aritcles.size > 15By #articles.seze > 15

Related

Rails 4 and search with Sunspot: is it possible to prevent n+1 queries when retrieving search results?

Take this code for example
#results = #search.results.nil? ? nil : #search.results.paginate(page: params[:page], :per_page => 10)
I am using the bullet gem, and because this is searching my "Posts" model and each "Post" has a link to the user, I am getting an n+1 query warning. I have tried
#results = #search.results.nil? ? nil : #search.results.includes(:user).paginate(page: params[:page], :per_page => 10)
But I get
undefined method `includes' for < <Sunspot::Search::PaginatedCollection:0x007f7f5cae5578>
Is there a way to more efficiently do this?
That's it:
Post.search(include: [:user])

Yii Undefined offset: 0 Using Query builder

It give error with this code:
$checklist = Yii::app()->db->createCommand()
->select('indicators, conditions, values, description')
->from('indicator')
->where([':indicators' => $kl_indicators[$i]])
->limit(1)
->queryAll();
"PHP notice:
Undefined offset: 0"
what is wrong with that code? Help please.
Thanks a lot.
Your params are wrong. It should be:
->where('indicators=:in', [':in'=>$kl_indicators[$i]] )
or:
->where('indicators = "'.$kl_indicators[$i].'"')
See the official API for more details.
Finally found this answer:
$checklist = Yii::app()->db->createCommand()
->select('id,conditions,indicators, values, description') //
->from('indicator')
//->group('indicators')
->order('id ASC')
->where('indicators=:indicators', [':indicators'=>$kl_indicators[$i]])
->queryAll();
Thank you Samuel Liew, i need all rows so i use queryAll().

Getting error "Can't convert FixNum into Array"

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.

ActiveRecord - NoMethodError

These AREL queries do not work in Rails 3. Can someone help me decipher this error?
NoMethodError (undefined method `id' for #<ActiveRecord::Relation:0xabf6f44>):
app/controllers/admin_controller.rb:206:in `save_user'
All of these cause the same error as shown above
#existing = Privilege.find(:first, :conditions => "b2b_user_id = #{#user.id} AND vendor_id = #{#vendor_id}")
#existing = Privilege.find_by_sql("SELECT * FROM b2b_privileges WHERE b2b_user_id = ? AND vendor_id = ? LIMIT 1",#user.id,#vendor_id)
#existing = Privilege.where(:b2b_user_id => #user.id, :vendor_id => #vendor_id)
But when I change this:
#user = B2bUser.where("id = ?",params[:id])
To this:
#user = B2bUser.find_by_id(params[:id])
The queries work. Why?
Thanks
What you're getting whn using method "where" is just a relation, think of it like a query that is still not executed, then you have to call a method to retrieve data eg: first, all, last, to_a, etc
#user = B2bUser.where("id = ?",params[:id]) #this is just an active record relation
#user = B2bUser.where("id = ?",params[:id]).first #this is your object
Read a little about relations, they're really interesting
relations

Rspec testing complex code with undefined variables

Just need alittle bit of help with rspec testing... very new to it and dont quite know how to test this piece of code
# Get a list of tasks recently used by the user
recent_task_ids = Effort.all( :select => "project_task_id",
:conditions => { :user_id => #user_id },
:group => "project_task_id",
:order => "MAX( week_commencing )" )
# For each of the task ids, get the actual project task records
#recent_tasks = []
recent_task_ids.each do |effort|
if ProjectTask.find_by_id( effort.project_task_id ) != nil
#recent_tasks.push( ProjectTask.find( effort.project_task_id ) )
end
end
Not sure if your even supposed to test undefined variables this way but any help would be great
You can stub out the Effort.all method.
it "tests with nil values" do
Effort.stub(:all).and_return(nil)
end
Source: http://rspec.info/documentation/mocks/stubs.html and http://rspec.info/documentation/mocks/