"Undefined method paginate" error message is coming while using will_paginate Gem - ruby

I am getting the following error when i am implementing will_paginate gem in my app.
Error:
NoMethodError in ProductsController#index
undefined method `paginate' for #<Array:0x2d25ae8>
app/controllers/products_controller.rb:3:in `index'
Please check my below code and please try to help me to resolve this.
Gemfile
source 'https://rubygems.org'
gem 'rails', '3.2.19'
# Bundle edge Rails instead:
# gem 'rails', :git => 'git://github.com/rails/rails.git'
gem 'sqlite3'
# Gems used only for assets and not required
# in production environments by default.
group :assets do
gem 'sass-rails', '~> 3.2.3'
gem 'coffee-rails', '~> 3.2.1'
# See https://github.com/sstephenson/execjs#readme for more supported runtimes
# gem 'therubyracer', :platforms => :ruby
gem 'uglifier', '>= 1.0.3'
end
gem 'jquery-rails'
# To use ActiveModel has_secure_password
# gem 'bcrypt-ruby', '~> 3.0.0'
# To use Jbuilder templates for JSON
# gem 'jbuilder'
# Use unicorn as the app server
# gem 'unicorn'
# Deploy with Capistrano
# gem 'capistrano'
# To use debugger
# gem 'debugger'
gem 'will_paginate', '~> 3.0'
views/products/index.html.erb
<%= will_paginate #products %>
<table style="width:500px">
<thead>
<tr>
<th>Name</th>
<th style="text-align:right;">Price</th>
<th style="text-align:right;">Quantity</th>
</tr>
</thead>
<tbody>
<% #products.each do |product| %>
<tr>
<td><%= product.name %></td>
<td style="text-align:right;"><%= number_to_currency product.price %></td>
<td style="text-align:right;"><%= product.quantity %></td>
</tr>
<% end %>
</tbody>
</table>
<%= will_paginate #products %>
controller/products_controller
class ProductsController < ApplicationController
def index
#products = Product.all.paginate(page: params[:page], per_page: 5)
end
end
Please try to help me.

Ah, just noticed you're on rails 3. In that case, try this instead:
#products = Product.paginate(page: params[:page], per_page: 5)
The difference is the lack of #all, which returns an Array on rails 3.

Related

How do I merge two or more results from elasticsearch rails gem?

I'm trying to merge two elasticsearch results into one variable, here my code tries...
class SearchController < ApplicationController
def index
end
def advanced
#results = {}
if !params[:fast_search].empty?
#results[:features] = TestCases.search(params[:fast_search]).results
#results[:steps] = Steps.search(params[:fast_search]).results
#results[:examples] = Examples.search(params[:fast_search]).results
else
unless params[:feature].blank?
features = TestCases.search(query: { match: { function: params[:feature] } }).results
features_tag = Steps.search(query: { match: { tags: params[:tags] } }).results
#results[:features] = features + features_tag
end
unless params[:steps].blank? || params[:scenario].blank?
#results[:steps] = Steps.search(query: { match: { scenario: params[:scenario] } }).results
params[:steps].each do |step|
#results[:steps] += Steps.search(query: { match: { steps: step } }).results
end
#results[:steps] += Steps.search(query: { match: { tags: params[:tags] } }).results
end
unless params[:examples].blank?
params[:examples].each do |example|
#results[:examples] += Examples.search(query: { match: { examples: example } }).results
end
#results[:examples] += Examples.search(query: { match: { tags: params[:tags] } }).results
end
unless params[:bug].blank?
#results[:miscs] = StepsMiscs.search(query: { match: { bug: true } }).results
end
end
render "search/index"
end
end
I also try features.merge(features_tag) but no success either.
It's simple, I just need to merge one and more results from the elasticsearch, but I simply don't know how.
Here's my Gemfile:
source 'https://rubygems.org'
# Bundle edge Rails instead: gem 'rails', github: 'rails/rails'
gem 'rails', '~> 5.0.0', '>= 5.0.0.1'
# Use sqlite3 as the database for Active Record
gem 'sqlite3'
# Use Puma as the app server
gem 'puma', '~> 3.0'
# Use SCSS for stylesheets
gem 'sass-rails', '~> 5.0'
# Use Uglifier as compressor for JavaScript assets
gem 'uglifier', '>= 1.3.0'
# Use CoffeeScript for .coffee assets and views
gem 'coffee-rails', '~> 4.2'
# See https://github.com/rails/execjs#readme for more supported runtimes
gem 'therubyracer', platforms: :ruby
# Use jquery as the JavaScript library
gem 'jquery-rails'
# Turbolinks makes navigating your web application faster. Read more: https://github.com/turbolinks/turbolinks
gem 'turbolinks', '~> 5'
# Build JSON APIs with ease. Read more: https://github.com/rails/jbuilder
gem 'jbuilder', '~> 2.5'
# Use Redis adapter to run Action Cable in production
# gem 'redis', '~> 3.0'
# Use ActiveModel has_secure_password
# gem 'bcrypt', '~> 3.1.7'
# Use Capistrano for deployment
# gem 'capistrano-rails', group: :development
# jQuery-Turbolinks
gem 'jquery-turbolinks'
# Mysql
gem 'mysql2'
# Safe Attributes
gem 'safe_attributes'
# Elastic Search
gem 'elasticsearch-model'
gem 'elasticsearch-rails'
gem 'elasticsearch-persistence'
gem 'pry'
#rake
gem 'rake'
#sidekiq
gem 'sidekiq'
group :development, :test do
# Call 'byebug' anywhere in the code to stop execution and get a debugger console
gem 'byebug', platform: :mri
end
group :development do
# Access an IRB console on exception pages or by using <%= console %> anywhere in the code.
gem 'web-console'
end
group :production do
#passenger
gem "passenger", require: "phusion_passenger/rack_handler"
end
# Windows does not include zoneinfo files, so bundle the tzinfo-data gem
gem 'tzinfo-data', platforms: [:mingw, :mswin, :x64_mingw, :jruby]
And here's obviously the error that I'm getting:
undefined method `+' for #<Elasticsearch::Model::Response::Results:0x0000000d2719f8>
Thanks!
Here after a lot of search, I've found this:
unless params[:steps].blank? || params[:scenario].blank? || params[:tags].blank?
query = Jbuilder.encode do |json|
json.query do
json.match do
json.scenario do
json.query params[:scenario]
end
end
params[:steps].each do |step|
json.match do
json.tags do
json.query step
end
end
end
json.match do
json.tags do
json.query params[:tags]
end
end
end
end
#results[:steps] = Steps.search(query).results
end
This help me to search more than one match on all my models.
I know that catch only the basics, but at the moment is part for what I need and I hope this could help all the others around here with the same issue!
Thanks you all!

getting wrong number argument error using Rails

Hi i am getting the following errors while using wicked_pdf gem in Rails3.
error:
ArgumentError in UsersController#download_pdf
wrong number of arguments (0 for 1)
Rails.root: C:/Site/generate4
Application Trace | Framework Trace | Full Trace
app/controllers/users_controller.rb:6:in `download_pdf'
After clicking on download pdf link the following error is coming.
error-2:
RuntimeError in UsersController#download_pdf
Error: Failed to execute:
["C:/Program Files/wkhtmltopdf/bin/wkhtmltopdf.exe", "--encoding", "UTF-8", "file://C:/DOCUME~1/SUBHRA~1/LOCALS~1/Temp/wicked_pdf20150527-1192-1qf0ac.html", "C:/DOCUME~1/SUBHRA~1/LOCALS~1/Temp/wicked_pdf_generated_file20150527-1192-fijfxt.pdf"]
Error: PDF could not be generated!
Command Error: Loading pages (1/6)
[> ] 0%
[======> ] 10%
Error: Failed loading page file://c/DOCUME~1/SUBHRA~1/LOCALS~1/Temp/wicked_pdf20150527-1192-1qf0ac.html (sometimes it will work just to ignore this error with --load-error-handling ignore)
Exit with code 1 due to network error: ContentNotFoundError
Please check my code below.
users_controller.rb:
class UsersController < ApplicationController
def index
end
def download_pdf
pdf=WickedPdf.new.pdf_from_string(
render_to_string pdf: "test.pdf", template: "users/test.html.erb", encoding: "UTF-8")
#save_path = 'C:\Site\download_pdf.pdf'
end
end
users/test.html.erb:
<h1>Hello rails</h1>
wicked_pdf.rb:
WickedPdf.config = {
#:wkhtmltopdf => '/usr/local/bin/wkhtmltopdf',
#:layout => "pdf.html",
:exe_path => 'C:/Program Files/wkhtmltopdf/bin/wkhtmltopdf.exe'
}
Gemfile:
source 'https://rubygems.org'
gem 'rails', '3.2.19'
gem 'sqlite3'
group :assets do
gem 'sass-rails', '~> 3.2.3'
gem 'coffee-rails', '~> 3.2.1'
gem 'uglifier', '>= 1.0.3'
end
gem 'jquery-rails'
gem 'wicked_pdf'
My requirement is convert HTML to PDF using Rails 3.Please help me to resolve this error and successfully get the PDF file.
Assuming, you are trying to download the pdf file.
see the code below:
#users_controller.rb:
class UsersController < ApplicationController
def download_pdf
pdf = render_to_string(pdf: "test.pdf", template: "users/test.html.erb", encoding: "UTF-8")
send_data pdf
end
end
# Gemfile
source 'https://rubygems.org'
gem 'rails', '3.2.19'
gem 'sqlite3'
group :assets do
gem 'sass-rails', '~> 3.2.3'
gem 'coffee-rails', '~> 3.2.1'
gem 'uglifier', '>= 1.0.3'
end
gem 'jquery-rails'
gem 'wicked_pdf', :github => 'mileszs/wicked_pdf', :branch => 'master'
Please check if it works.

How to convert html table to PDF using Rails 3

I am trying to generate one PDF file using Rails 3. I have a table with some values and i want to display these data in PDF. I have written some code which are explained below.
index.html.erb:
<h1>Choose the option</h1>
<p>
<%= link_to "new input",products_new_path %>
</p>
<table>
<tr>
<th>Product name</th>
<th>Product Catagory</th>
</tr>
<% #product.each do |p| %>
<tr>
<td><%= p.p_name %></td>
<td><%= p.p_catagory %></td>
</tr>
<% end %>
</table>
products_controller.rb:
class ProductsController < ApplicationController
def index
#product=Product.all
respond_to do |format|
format.html
format.pdf do
pdf = Prawn::Document.new
send_data pdf.render, filename: 'report.pdf', type: 'application/pdf'
end
end
end
def new
#product=Product.new
end
def create
#product=Product.new(params[:product])
if #product.save
flash[:notice]="Data submitted"
flash[:color]="valid"
redirect_to :action => "index"
else
flash[:alert]="Data could not finish"
flash[:color]="invalid"
render 'new'
end
end
end
Gemfile:
source 'https://rubygems.org'
gem 'rails', '3.2.19'
# Bundle edge Rails instead:
# gem 'rails', :git => 'git://github.com/rails/rails.git'
gem 'sqlite3'
# Gems used only for assets and not required
# in production environments by default.
group :assets do
gem 'sass-rails', '~> 3.2.3'
gem 'coffee-rails', '~> 3.2.1'
# See https://github.com/sstephenson/execjs#readme for more supported runtimes
# gem 'therubyracer', :platforms => :ruby
gem 'uglifier', '>= 1.0.3'
end
gem 'jquery-rails'
# To use ActiveModel has_secure_password
# gem 'bcrypt-ruby', '~> 3.0.0'
# To use Jbuilder templates for JSON
# gem 'jbuilder'
# Use unicorn as the app server
# gem 'unicorn'
# Deploy with Capistrano
# gem 'capistrano'
# To use debugger
# gem 'debugger'
gem 'prawn'
config/initializer/mime_type.rb
Mime::Type.register "application/pdf", :pdf
Please help me to resolve this issue and also let me to know how can i run app(e.g-localhost:3000/products.pdf) for getting this pdf file.
What I would do is to add this line to your Gemfile to generate a table with prawn :
gem 'prawn-table'
Make sure you are using these version :
bundle show
# * prawn (2.0.1)
# * prawn-table (0.2.1)
In your controller, if you want to generate the PDF file when index action is called you can add this into it :
def index
#products = Product.all
require "prawn/table"
require "prawn"
Prawn::Document.generate("test.pdf") do |pdf|
table_data = Array.new
table_data << ["Product name", "Product category"]
#products.each do |p|
table_data << [p.name, p.category]
end
pdf.table(table_data, :width => 500, :cell_style => { :inline_format => true })
end
end
You can add some html syntax if you want to it :
["<b>#{p.name}</b>", "<i>#{p.category}</i>"]
Here is the result :
#satya, I'll suggest you to use 'prawn' and 'prawn-table' gem.
Steps to create pdf is -
1: #create pdf object
pdf = Prawn::Document.new()
2: #assign the value in pdf object
pdf.text "To Date - #{extra_data[:to_date]}"
For more info you can watch this vedio -
http://railscasts.com/episodes/153-pdfs-with-prawn
#satya, use this- - > return send_data Product.get_product_report_runtime_pdf(input_data), type: :pdf, filename: "Units_report_#{Time.now.strftime("%Y%m%d%H%M%S")}.pdf" will return the run time created pdf and if you want html page as well then dont use return before send data.
Under Product model -> here I am returning the blank pdf, so use the required code whatever you want in your pdf.
def get_product_report_runtime_pdf
pdf = Prawn::Document.new
return pdf.render
end

SQLite3::SQLException: no such table: messages: SELECT "messages".* FROM "messages"

I am making a simple chat app based on this railscast. I posted another question about this, but I stupidly did not add a model, and then I named it incorrectly.
However, that is now fixed. The thing is, I am not even sure if I need a database at all. I was originally going to finish this, then upload it on heroku to just play around with. I don't want to store the messages, but if it is necessary then I will. Here is my code.
index.html.erb
<h1>Hack Chat</h1>
<ul id="chat">
<%= render #messages %>
</ul>
<%= form_for Message.new, remote: true do |f| %>
<%= f.text_field :content %>
<%= f.submit "Send" %>
<% end %>
<%= subscribe_to "/messages/new" %>
controller;
class MessagesController < ApplicationController
def index
#messages = Message.all
end
def create
#message = Message.create!(params[:message])
PrivatePub.publish_to("/messages/new", "alert('#{#message.content}');")
end
end
model;
class Message < ActiveRecord::Base
end
routes;
Hackchat::Application.routes.draw do
root to: 'messages#index'
resources :messages
end
gemfile;
source 'https://rubygems.org'
gem 'rails', '4.0.0'
gem "rake", "~> 10.1.1"
gem 'sqlite3'
group :assets do
gem 'sass-rails', '~> 4.0.0'
gem 'uglifier', '>= 1.3.0'
gem 'coffee-rails', '~> 4.0.0'
end
gem 'jquery-rails'
gem 'private_pub'
gem "thin", "~> 1.6.1"
I ran bundle exec rake db:create, bundle exec rake db:migrate and I still get the error;
ActionView::Template::Error (SQLite3::SQLException: no such table: messages: SELECT "messages".* FROM "messages"):
1: <h1>Hack Chat</h1>
2:
3: <ul id="chat">
4: <%= render #messages %>
5: </ul>
6:
7: <%= form_for Message.new, remote: true do |f| %>
app/views/messages/index.html.erb:4:in `_app_views_messages_index_html_erb__3441634471849115078_70351149151260'
Any and all help would be greatly appreciated.
#messages = Message.all
Tells the Rails app to query the db for every message in the message table. So if you want to use a
Rails app in that way, then yes you would have to have some sort of a messages table. You said you are not looking to store the messages so the index action should go to a blank chat screen. So just get rid of #messages = Message.all. If you wanted to have a scrolling list of chat messages I guess you could just write each line to an array and have the index page show that. Just set that array to be blank at the beginning of a chat session.

Uninitialized Constant MessagesController

I'm building a simple chat app based on this rails cast. I'm following along fine, but when I go to localhost, I get an error "uninitialized constant MessagesController::Message". This is generally a simple fix, but I have spent over an hour looking for the fix and I cannot see it. Here is my code;
messages_controller
class MessagesController < ApplicationController
def index
#messages = Message.all
end
def create
#message = Message.create!(params[:message])
PrivatePub.publish_to("/messages/new", "alert('#{#message.content}');")
end
end
model (message.rb)
class Message
end
index & message form (index.html.erb);
<h1>Hack Chat</h1>
<ul id="chat">
<%= render #messages %>
</ul>
<%= form_for Message.new, remote: true do |f| %>
<%= f.text_field :content %>
<%= f.submit "Send" %>
<% end %>
<%= subscribe_to "/messages/new" %>
routes.rb;
Hackchat::Application.routes.draw do
root to: 'messages#index'
resources :messages
end
gemfile;
source 'https://rubygems.org'
gem 'rails', '4.0.0'
gem 'sqlite3'
group :assets do
gem 'sass-rails', '~> 4.0.0'
gem 'uglifier', '>= 1.3.0'
gem 'coffee-rails', '~> 4.0.0'
end
gem 'jquery-rails'
gem 'private_pub'
gem "thin", "~> 1.6.1"
I have checked every possible thing I could think of as to why I would be getting this error, and I really do not know why. Any help would be much appreciated.
Also, for using private pub, do I have to run two terminal windows, one running rails server, and the other running faye?
Your model is #Messages, change it to #message.
To change it like you should use migration:
def change
rename_table :old_table_name, :new_table_name
end
Of course do not create that file by hand but use rails generator:
rails g migration ChangeMessagesToMessage
That will generate new file with proper timestamp in name in 'db dir. Then run:
rake db:migrate
And your app should be fine since then.

Resources