Decided to JSONify with Redis my site. How do I get will_paginate to work with json?
# games.html.erb
<%= js_will_paginate #games, renderer: BootstrapPagination::Rails, class: 'pagination-sm', previous_label: "←".html_safe, next_label: "→".html_safe, page_links: false %>
This is the error I get:
# undefined method `total_pages' for #<Array:0x007f90ebc05cf0> ln 23 of will_paginate_helper.rb
ln23: will_paginate(collection, options.merge(:renderer => WillPaginateHelper::WillPaginateJSLinkRenderer))
And my will_paginate_helper:
# will_paginate_helper.rb
module WillPaginateHelper
class WillPaginateJSLinkRenderer < BootstrapPagination::Rails
def prepare(collection, options, template)
options[:params] ||= {}
options[:params]['_'] = nil
super(collection, options, template)
end
protected
def link(text, target, attributes = {})
if target.is_a? Fixnum
attributes[:rel] = rel_value(target)
target = url(target)
end
#template.link_to(target, attributes.merge(remote: true)) do
text.to_s.html_safe
end
end
end
def js_will_paginate(collection, options = {})
will_paginate(collection, options.merge(:renderer => WillPaginateHelper::WillPaginateJSLinkRenderer))
end
end
when I play around with the cli below the nomethoderror exception...
>> collection
=> [{"id"=>8199, "start_time"=>nil, "game_date"=>"2016-10-23", ... etc }]
>> collection.first
=> {"id"=>8199, "start_time"=>nil, ... etc
Do I need to convert collection to something will_paginate can work with or do I re-write/override js_will_paginate? Thank you!
Figured it out.
added require 'will_paginate/array' to my will_paginate_helper.rb and then paginated the collection AFTER .to_json, e.g. in my helper (or your controller):
games = Game.order(game_date: :desc).postgame.to_json
#games = Oj.load games
#games = #games.paginate(page: params[:page], per_page: 10)
Works with will_paginate or js_will_paginate just as before.
Related
wrong number of arguments (given 2, expected 1)
SportsController
class SportsController < ApplicationController
def index
#sport = Sport.all
#events, #errors = Bapi::Inplay.all(query)
end
private
def query
params[:query, {}]
end
end
Sport index.html.erb
<% #sports.each do |sport| %>
<% #events(:sport_id => sport.id).each_slice(2) do |events| %>
I want send each sport.id to #enevts instance variable
Edited :
When send query as hash in SportsController its work!!
class SportsController < ApplicationController
def index
#sport = Sport.all
query = {:sport_id => 1}
#events, #errors = Bapi::Inplay.all(query)
end
private
def query
params[:query, {}]
end
end
Index.html.erb
<% #sports.each do |sport| %>
<% #events.each_slice(2) do |events| %>
params is a hash and method :[] can accept only 1 argument.
def query
params[:query] || {} # Will return :query part or empty Hash if it has nothing
end
So, I have followed the standard answers for applying will paginate WITH AJAX on my rails website, but it doesn't seem to be working. If I click to go to the next set of partials, the page doesn't change. I see the request being made, but the contents of the page are the same.
//Here is my code below:
//Views
#container.baseGrip
= render :partial => 'student_search_pages/search_options'
#teachersList.full
%span.noreselt.full 該当する先生はいません
- #initial_users.each do |user|
.profcard_wrapper.six
= render :partial => "user_profile_cards/user_profile_card", :locals => {:user => user, :favorite_view => true}
= render :partial => 'users/edit/sche_candidate'
= js_will_paginate #initial_users, :previous_label => "< b", :next_label => "n >", :class => "pagination full", :outer_window => 2, :params => params[:page]
Here is my controller:
class StudentSearchPagesController < AuthenticatedController
before_action :check_user_is_student!
include StudentSearchPagesHelper
include WillPaginateHelper
def show
#user = current_user
#student = current_user.student
#initial_users = StudentSearchPagesHelper.initial_teacher_search(#student).paginate(:page => params[:page], :per_page => 1)
#favorites = current_user.user_favorites
#referer = request.referer
end
end
And finally, here is my helper:
module WillPaginateHelper
class WillPaginateJSLinkRenderer < WillPaginate::ActionView::LinkRenderer
def prepare(collection, options, template)
options[:params] ||= {}
options[:params]['_'] = nil
super(collection, options, template)
end
protected
def link(text, target, attributes = {})
if target.is_a? Fixnum
attributes[:rel] = rel_value(target)
target = url(target)
end
#template.link_to(target, attributes.merge(remote: true)) do
text.to_s.html_safe
end
end
end
def js_will_paginate(collection, options = {})
will_paginate(collection, options.merge(:renderer => WillPaginateHelper::WillPaginateJSLinkRenderer))
end
end
Also, here is the request that shows up when I click next:
Started GET "/student/search?page=2" for ::1 at 2018-04-04 10:09:13 -0400
Processing by StudentSearchPagesController#show as JS
Parameters: {"page"=>"2"}
...
Rendered users/edit/_time.haml (284.7ms)
Rendered user_profile_cards/_teacher_card.haml (456.3ms)
Rendered user_profile_cards/_user_profile_card.haml (542.3ms)
Subject Load (1.0ms) SELECT `subjects`.* FROM `subjects` ORDER BY `subjects`.`id` ASC LIMIT 1000
Rendered users/edit/_sche_candidate.haml (8.0ms)
Matching Load (0.7ms) SELECT `matchings`.* FROM `matchings` WHERE `matchings`.`student_id` = 2
Rendered student_search_pages/show.haml (1223.8ms)
This helper I use and works perfectly:
module WillPaginateHelper
class WillPaginateAjaxLinkRenderer < WillPaginate::ActionView::LinkRenderer
def prepare(collection, options, template)
options[:params] ||= {}
options[:params]["_"] = nil
super(collection, options, template)
end
protected
def link(text, target, attributes = {})
if target.is_a? Fixnum
attributes[:rel] = rel_value(target)
target = url(target)
end
target = target.sub('/data', "") if Rails.env == "production"
ajax_call = "$.ajax({url: '#{target}', dataType: 'script'});return false;"
#template.link_to(text.to_s.html_safe,"#", onclick: ajax_call)
end
end
def ajax_will_paginate(collection, options = {})
will_paginate(collection, options.merge(:renderer => WillPaginateHelper::WillPaginateAjaxLinkRenderer))
end
end
in my Rails 3.2.2 app I'm trying to use i18n but something is not working correctly.
In fact the "t" method does not work, only "i18n.t" works.
So, for example:
t(:login)
=> login
Instead:
i18n.t(:login)
=> Provide the necessary login info
Can you help me to figure out what I'm doing wrong?
Thanks,
Augusto
UPDATE
I used pry to show the source for the t helper and got this:
From: /Users/phishman/.rvm/gems/ruby-1.9.2-p290/gems/actionpack-3.2.2/lib/action_view/helpers/translation_helper.rb # line 46:
Number of lines: 16
Owner: ActionView::Helpers::TranslationHelper
Visibility: public
def translate(key, options = {})
options.merge!(:rescue_format => :html) unless options.key?(:rescue_format)
if html_safe_translation_key?(key)
html_safe_options = options.dup
options.except(*I18n::RESERVED_KEYS).each do |name, value|
unless name == :count && value.is_a?(Numeric)
html_safe_options[name] = ERB::Util.html_escape(value.to_s)
end
end
translation = I18n.translate(scope_key_by_partial(key), html_safe_options)
translation.respond_to?(:html_safe) ? translation.html_safe : translation
else
I18n.translate(scope_key_by_partial(key), options)
end
end
3] pry(main)> show-source helper.t
From: /Users/phishman/.rvm/gems/ruby-1.9.2-p290/gems/actionpack-3.2.2/lib/action_view/helpers/translation_helper.rb # line 46:
Number of lines: 16
Owner: ActionView::Helpers::TranslationHelper
Visibility: public
def translate(key, options = {})
options.merge!(:rescue_format => :html) unless options.key?(:rescue_format)
if html_safe_translation_key?(key)
html_safe_options = options.dup
options.except(*I18n::RESERVED_KEYS).each do |name, value|
unless name == :count && value.is_a?(Numeric)
html_safe_options[name] = ERB::Util.html_escape(value.to_s)
end
end
translation = I18n.translate(scope_key_by_partial(key), html_safe_options)
translation.respond_to?(:html_safe) ? translation.html_safe : translation
else
I18n.translate(scope_key_by_partial(key), options)
end
end
the t method is a helper and therefore only available in views and controllers.
If you try to use I18n from models or the rails console, you should use I18n.t
I am using Rails 3.0.9 . I am trying to use liquid and I am getting an error.
Here is my Gemfile
source 'http://rubygems.org'
gem 'rails', '3.0.9'
gem 'sqlite3'
gem 'liquid'
Here is an initializer
class LiquidView
PROTECTED_ASSIGNS = %w( template_root response _session template_class action_name request_origin session template
_response url _request _cookies variables_added _flash params _headers request cookies
ignore_missing_templates flash _params logger before_filter_chain_aborted headers )
PROTECTED_INSTANCE_VARIABLES = %w( #_request #controller #_first_render #_memoized__pick_template #view_paths
#helpers #assigns_added #template #_render_stack #template_format #assigns )
def self.call(template)
"LiquidView.new(self).render(template, local_assigns)"
end
def initialize(view)
#view = view
end
def render(template, local_assigns = nil)
#view.controller.headers["Content-Type"] ||= 'text/html; charset=utf-8'
# Rails 2.2 Template has source, but not locals
if template.respond_to?(:source) && !template.respond_to?(:locals)
assigns = (#view.instance_variables - PROTECTED_INSTANCE_VARIABLES).inject({}) do |hash, ivar|
hash[ivar[1..-1]] = #view.instance_variable_get(ivar)
hash
end
else
assigns = #view.assigns.reject{ |k,v| PROTECTED_ASSIGNS.include?(k) }
end
source = template.respond_to?(:source) ? template.source : template
local_assigns = (template.respond_to?(:locals) ? template.locals : local_assigns) || {}
if content_for_layout = #view.instance_variable_get("#content_for_layout")
assigns['content_for_layout'] = content_for_layout
end
assigns.merge!(local_assigns.stringify_keys)
liquid = Liquid::Template.parse(source)
liquid.render(assigns, :filters => [#view.controller.master_helper_module], :registers => {:action_view => #view, :controller => #view.controller})
end
def compilable?
false
end
end
::ActionView::Template.register_template_handler(:liquid, LiquidView)
Here is app/views/users/index.html.liquid
<h1>Listing users</h1>
<table>
<tr>
<th>Name</th>
</tr>
{% for user in #users %}
<tr> <td> {{ user.name }} </td> </tr>
{% endfor %}
</table>
And here is controller
class UsersController < ApplicationController
def index
#users = User.all
respond_to do |format|
format.html # index.html.erb
end
end
end
I am getting this error.
undefined method `template' for #<UsersController:0x00000100979b80>
Extracted source (around line #1):
1: <h1>Listing users</h1>
2:
3: <table>
4: <tr>
I think this should help you, just change initializer with code below
class LiquidView
def self.call(template)
"LiquidView.new(self).render(#{template.source.inspect}, local_assigns)"
end
def initialize(view)
#view = view
end
def render(template, local_assigns = {})
#view.controller.headers["Content-Type"] ||= 'text/html; charset=utf-8'
assigns = #view.assigns
if #view.content_for?(:layout)
assigns["content_for_layout"] = #view.content_for(:layout)
end
assigns.merge!(local_assigns.stringify_keys)
controller = #view.controller
filters = if controller.respond_to?(:liquid_filters, true)
controller.send(:liquid_filters)
elsif controller.respond_to?(:master_helper_module)
[controller.master_helper_module]
else
[controller._helpers]
end
liquid = Liquid::Template.parse(template)
liquid.render(assigns, :filters => filters, :registers => {:action_view => #view, :controller => #view.controller})
end
def compilable?
false
end
end
ActionView::Template.register_template_handler :liquid, LiquidView
just don't forget to put liquid_methods [,:column_name] to your model
I am using a block method to print a list, but it is generating error.
class MyDataListBuilder
attr_accessor :object
def initialize(object)
#object = object
end
def column (&block)
content_tag :li, block.call
end
end
and using it as
<%= my_data_list_for #leads, [" :10", "Age:30", "Contact:140", "Phone:140", "Email:180", "Company:100", ""] do |l| %>
<%= l.column do %>
<%= object.age %>
<% end %>
<% end %>
other methods are
def list_headers(args=[])
args = Array.new(args)
columns = []
args.map { |o| columns << content_tag(:li, o.split(":").first, :style=>"width:#{o.split(":").second}px;") }
content_tag(:ul, columns.join(" ").html_safe, :class=>"list-headers")
end
def my_data_list_for(object, headers=[], &block)
arr = []
object.each do |o|
arr = capture(DataListHelper::MyDataListBuilder.new(o), &block)
end
content_tag(:ol, list_headers(headers) + arr, :class=>"data-list")
end
it is generating an error and i can not figure out why:
ActionView::Template::Error (undefined local variable or method `object' for #<#<Class:0xcaa1ca0>:0xca9ebf4>):
Please help me in it.
This solves the issue.
class MyDataListBuilder
include ActionView::Helpers::TagHelper
include ActionView::Helpers::CaptureHelper
attr_accessor :object, :output_buffer
def initialize(object)
#object = object
#output_buffer = nil
end
def column (&block)
if block_given?
content_tag(:li, capture(self, &block))
else
content_tag(:li, "")
end
end
end