`undefined method `group_by_day' for 10:Fixnum` with Chartkick - ruby-on-rails

I'm trying to make a chart using Chartkick and am getting this error: undefined method 'group_by_day' for 10:Fixnum.
As recommended by this SO post, I installed the gem groupdate, so that isn't the problem.
My index method from my tasks_controller is:
def index
#tasks = Task.where(user_id: current_user.id).order("created_at DESC")
end
And my erb in tasks#index is:
<%= line_chart #tasks.map { |task|
{name: task.name, data: task.reps.group_by_day(:created_at)}
} %>
Can anyone see where I'm going wrong here?

Related

No method error when using pagy gem -Ruby on Rails

I am trying to use pagy gem but I am getting no method error.
In my controller, I previously have
def index
#hires = [*current_user.student_hires.order('created_at desc')]
current_user.groups.includes(:group_hires).each do |group|
#hires.push(*group.group_hires.order('created_at desc'))
end
#hires = #hires.uniq(&:id)
end
but since I want to use Pagy, I changed it to
def index
#pagy, #hires = pagy([*current_user.student_hires.order('created_at desc')])
current_user.groups.includes(:group_hires).each do |group|
#hires.push(*group.group_hires.order('created_at desc'))
end
#hires = #hires.uniq(&:id)
end
and in my view, I have
<%== render partial: 'pagy/nav', locals: {pagy: #pagy} %>
But I am getting
undefined method `offset' for [#<Hire id: 12, grade: "Grade 1"
I am using pagy in another simpler controller and it works well but I can't get it to work on this controller index.
I was able to fix it using pagy_array
So I did
#pagy, #hires = pagy_array([*current_user.student_hires.order('created_at desc')])
and also added require 'pagy/extras/array' to the config/initializers
More instruction about it is here https://ddnexus.github.io/pagy/extras/array#gsc.tab=0

Defining a method

I am new to coding & I am taking ruby on rails online class. I have followed the lecture and documented everything but I am getting "NonMethod" error. Here what I have in my file
Controller
class CoursesController < ApplicationController
def index
#search_term = 'jhu'
#courses = Coursera.for(#search_term)
end
end
Model
class Coursera
include HTTParty
base_uri 'https://api.coursera.org/api/catalog.v1/courses'
default_params fields: "smallIcon,shortDescription", q: "search"
format :[enter image description here][1]json
def self.for term
get("", query: { query: term})["elements"]
end
end
Views
<h1>Searching for - <%= #search_term %></h1>
<table border="1">
<tr>
<th>Image</th>
<th>Name</th>
<th>Description</th>
</tr>
<% #courses.each do |course| %>
<tr class=<%= cycle('even', 'odd') %>>
<td><%= image_tag(course["smallIcon"])%></td>
<td><%= course["name"] %></td>
<td><%= course["shortDescription"] %></td>
</tr>
<% end %>
</table>
These are the messages I am getting
NoMethodError in Courses#index
Showing /Users/Dohe/my_app/app/views/courses/index.html.erb where line #11 raised:
undefined method `each' for nil:NilClass
Can any help me with what I am doing wrong
Ruby 2.2.9 and Rails 4.2.3
Check what #courses contains in the controller, and change <% end %> to <% end if #courses.present? %> in your view, Its just making sure to only try to iterate through the #courses and populate it in the view if it actually contains any data, if it is nil then nil does not have a each method defined for it so you're getting the
undefined method `each' for nil:NilClass
As Subash stated in the comment, #courses is nil, which means that:
get("", query: { query: term})["elements"]
is returning nil. So, when you try #courses.each, you're getting the NoMethod error.
If you expect:
get("", query: { query: term})["elements"]
not to be nil, then you'll have to debug that. You could show us your console logs and we might be able to help with that.
Also, to protect from the NoMethod error, you could do:
def self.for term
get("", query: { query: term})["elements"] || []
end
This says, essentially, "return an empty array if get("", query: { query: term})["elements"] is nil". This will resolve your error, but could mask other problems you might be having. So, proceed with caution.

Error when using HTTParty gem to consume API: undefined method `[]' for nil:NilClass

I keep getting this error: "undefined method `[]' for nil:NilClass" while trying to parse JSON using HTTParty in Ruby on Rails.
I want to be able to consume an API, but am unable to get anything to work.
The URL works fine and returns JSON elements with no problem; I am just unable to access them and present them for some strange reason.
I am using Rails 5 and Ruby 2.4. All API keys are hidden, but are properly input into my Rails app.
Here is my lib file:
require 'httparty'
class Wunderground
include HTTParty
format :json
base_uri 'api.wunderground.com'
attr_accessor :temp, :location, :icon, :desc, :url, :feel_like
def initialize(response)
#temp = response['current_observation']['temp_f']
#location = response['current_observation']['display_location']['full']
#icon = response['current_observation']['icon_url']
#desc = response['current_observation']['weather']
#url = response['current_observation']['forecast_url']
#feel_like = response['current_observation']['feelslike_f']
end
def self.get_weather(state, city)
response = get("/api/#{ENV["wunderground_key"]}/conditions/q/#{state}/#{city}.json")
if response.success?
new(response)
else
raise response.response
end
end
end
I've entered my api key into my application.yml file like so:
wunderground_key: "YOUR_API_KEY"
My controller:
class HomeController < ApplicationController
require 'Wunderground'
def wunderground
#weather = Wunderground.get_weather(params[:state], params[:city])
end
def index
end
end
My routes:
root 'home#index'
get 'wunderground', to: 'home#wunderground'
My view:
<div>
<%= form_tag wunderground_path, method: "get", class: "form-inline" do %>
<%= text_field_tag :city, nil, class: "form-control", placeholder: "City Name" %>
<%= select_tag :state, options_for_select(#states), :prompt => "Please select", class: "form-control" %>
<%= submit_tag "Check Weather", name: nil, class: "btn btn-primary" %>
<% end %>
</div>
<div>
<% if #weather.present? %>
<h3><%= #weather.location %></h3>
<p>The temperature is:
<%= #weather.temp %></p>
<p>Feels like:
<%= #weather.feel_like %></p>
<p>
<%= #weather.desc %>
<%= image_tag #weather.icon %>
</p>
<p>
<%=link_to "Full Forecast", #weather.url, target: "_blank" %>
</p>
</div>
<% end %>
Edit:
This is the error that I am getting as shown in the development log:
NoMethodError (undefined method `[]' for nil:NilClass):
lib/Wunderground.rb:12:in `initialize'
lib/Wunderground.rb:23:in `new'
lib/Wunderground.rb:23:in `get_weather'
app/controllers/home_controller.rb:6:in `wunderground'
Source of error
You're getting this error, because response['current_observation'] is nil.
Debugging strategy
To arrive at this conclusion, we typically look at the error message, and the line of code the error is originating from.
From your question, it's clear that you already know what the error is: undefined method '[]' for nil:NilClass, and if you look at the stack trace, your error is coming from lib/Wunderground.rb:12:in initialize'.
The relevant line of code is this:
#temp = response['current_observation']['temp_f']
In Ruby, object['foo'] is a syntax sugar for the "call the [] method on object with argument 'foo'. It can also be described as "send [] message to object with an argument 'foo'.
Chained [][] calls are just calling the same method on the returned object.
In effect, you are calling [] with 'current_observation' on response, and then calling [] on the returned object with 'temp_f'. What this means, is that you're calling [] on 2 objects:
response
Object returned by response['current_observation']
Looking at the error, undefined method '[]' for nil:NilClass, tells us that one of the above two objects is nil.
Since in a previous call response.success? returned true, we can conclude response['current_observation'] is indeed returning nil.
Further debugging and finding ways to fix this
There are a few options.
Pretty print the response: pp response.parsed_response.
Use the debug_output setting from HTTParty to look at the HTTP request response log.
class Wunderground
include HTTParty
format :json
debug_output $stdout
# ...
# rest of the code
# ...
end
With debug mode on, watch the server log so you can get an idea about what response is the API returning.

rails search returns array in dev but nil in heroku productuon environment

I made a search form in which works perfectly in my dev environment but doen't work in my heroku instance. When I debug, it looks like the search result array is null in production. I made sure I have seed data in the database.
home.html.erb
<%= form_tag("home", method: "get") do %>
<%= text_field_tag :search, params[:search] %>
<%= submit_tag 'Search', name: nil %>
<% end %>
<% if #search_results.any? %>
<ul><%= render #search_results %></ul>
<%= will_paginate #search_results %>
<% end %>
static_pages_controller.rb
def home
if params[:search] then
#search_results = Foo.where('bar LIKE ?', "%#{params[:search]}%").paginate(page: params[:page])
else
#search_results = Foo.order("bar DESC").paginate(page: params[:page])
end
end
I get #search_results.any? == false when I run this code in heroku so no results are printed, which is not the case when I run locally. Not sure what I am missing.
Edit:
It tried querying via rails console on both dev and heroku. I used the same code on the same seed data but heroku really returns nil. Is it something database related, cos I know they use different databases. Here's the line:
Foo.where('bar LIKE ?', "%baz%").paginate(page: 1)
The issue is caused by peculiarities in the database.
Local installation of rails uses SQLite3 which is not case-sensitive when it comes to the WHERE clause. Heroku's PostgreSQL is case-sensitive so that when you query Foo.where('bar LIKE ?', "%baz%") where actually bar == 'Baz', you will get results in dev but not in heroku.
It is best to use LOWER() before comparing values. In this case, replace
Foo.where('bar LIKE ?', "%baz%")
with
Foo.where('LOWER(bar) LIKE LOWER(?)', "%baz%")

Error with Kaminari pagination

I would like to paginate my objects with the Kaminari pagination gem. I have this line in my controller:
#products = Product.order("id").find_all_by_id(params[:id])
That line in my view:
<%= paginate #products %>
And that line in my model:
paginates_per 20
When I open my page where my objects are supposed to be listed, I have this error message :
undefined method `current_page' for #<Array:0x2964690>
The exception is raised at my <%= paginate #products %> line.
I have already made a pagination for another project and it was working really great. Could someone help me please ?
Thank you !
Edit:
The problem is that find_all_by_* returns an array, not an ActiveRecord::Relation.
You can do something like this instead
#products = Product.order("id").where("id IN (?)", params[:id])
Also, you should probably have a .page(params[:page]) in there.

Resources