Rails 3: Sortable Columns - ruby-on-rails-3

I'm following Railscasts #228 in Rails 3.0.5 and ruby 1.9.2p180.
I have copied code near verbatim from the verbatim with the exception of changing the class name from Product to Player. I'm also skipping the last portion where Ryan adds arrows to denote the sort direction. I'm able to load the correct index page and see all of the desired URL's with the desired parameters (direction and sort), but nothing is actually happening on click. The URL is changing, but the page is not reloading.
Here is my code:
ApplicationHelper
def sortable(column, title = nil)
title ||= column.titleize
direction = (column == params[:sort] && params[:direction] == "asc") ? "desc" : "asc"
link_to title, :sort => column, :direction => direction
end
PlayersController
def index
#players = Player.order(sort_column + ' ' + sort_direction)
end
private
def find_team
session[:team] ||= Team.new
end
def sort_column
Player.column_names.include?(params[:sort]) ? params[:sort] : "name_e"
end
def sort_direction
%w[asc desc].include?(params[:direction]) ? params[:direction] : "asc"
end
Thanks for your help!
Edit: As requested, HTML code. You can see that the link for Position is currently desc, as I am at: http://localhost:3000/players?direction=asc&sort=abb_pos. However, no actual sorting has occurred for this column, or any other column.
<th>Name</th>
<th>Team</th>
<th>Position</th>
<th>Height</th>
<th>Weight</th>

Nathan
I'd suggest doing this first thing:
def index
order = sort_column + ' ' + sort_direction
puts "-- order:'#{order}'"
...
end
Click the links and then look in server's console for that "--" output. Most probably there's a logical flaw somewhere that makes the actual compiled ORDER clause always be the same. Links themselves look perfectly okay. Unless there's a # character in the links somewhere, all clicks should work (i.e. the browser should reload the content).
As for the problem in general, there's a gem called handles_sortable_columns, which gets you sortable columns for no effort at all.
Alex

Found the issue. I had the following code in my player model:
Player.rb
default_scope :order => 'name_e'
As a result, the SQL search generated looked like this:
SELECT `players`.* FROM `players` ORDER BY name_e, avg_points desc

Related

undefined method `order' for []:Array

I have the following code where I load the activities for the user based on whether or not they are an admin. Users can only see their own activity feed, whereas admins can see the entire stream. This is a precursor to sharing activity feeds with friends, etc.
def index
if current_user?
#incidents = Incident.find_all_by_user_id(current_user.id).order("created_at desc")
else
#incidents = Incident.all.order("created_at desc")
end
end
I am getting the above referenced error(undefined method "order" for []:Array). It seems to be the .order reference, but I have checked the rails Guides and it seems to be correct syntax.
Any ideas?
Try changing the find_by... to where, so:
def index
if current_user?
#incidents = Incident.where(user_id: current_user.id).order("created_at desc")
else
#incidents = Incident.all.order("created_at desc")
end
end
should work :-)
The #index action method can be simplified and optimized (by replacement find_all_by with where) to:
def index
clause = current_user? && Incident.where(user_id: current_user.id) || Incident
#incidents = clause.order("created_at desc")
end

Why are ampersands escaped when generating url with link_to?

Here is my simple rails 3 code :
<%= link_to "link", gateway_index_url(developer:#item.developer.api_key, tracker:"email", url:#product.url) %>
And the result is :
<a href="/gateway?developer=abcde&tracker=email&url=http%3A%2F%2Fwww.bla.fr%2FproductA" >link</a>
The problem is that & are rewritten in &. I can't figure how to prevent escaping, as :escape => false doesn't exist in Rails 3
Update: So here's the source
def link_to(*args, &block)
if block_given?
options = args.first || {}
html_options = args.second
link_to(capture(&block), options, html_options)
else
name = args[0]
options = args[1] || {}
html_options = args[2]
html_options = convert_options_to_data_attributes(options, html_options)
url = url_for(options)
href = html_options['href']
tag_options = tag_options(html_options)
href_attr = "href=\"#{ERB::Util.html_escape(url)}\"" unless href
"<a #{href_attr}#{tag_options}>#{ERB::Util.html_escape(name || url)}</a>".html_safe
end
end
As we can see, from the source, this behavior is by design.
You can try one of two solutions, I haven't tried them but they should work
1.) Try placing the call to gateway inside of a call to #raw:
<%= link_to "link", raw(gateway_index_url(developer: #item.developer.api_key, tracker:"email", url:#product.url)) %>
That may solve your specific problem, an the second approach, while a bit more brute-force should also work...
2.) If you want to convert it (the whole href) back you can... use CGI::unescape_html:
<%= CGI::unescape_html(link_to "link", gateway_index_url(developer: #item.developer.api_key, tracker:"email", url:#product.url)) %>
Good luck, hopefully this helps.
Update 2: Fixed call to cgi unescape, was using "." when it should be "::" and formatting fix. Forgot to indent example for #1
Rory O'Kane is spot on. The answer to "Why are ampersands escaped when generating url with link_to?" is that is the correct way to separate params in a url.
Is there a problem with the url the way it is?
If so, could you elaborate on the problem?
You may be able to prevent escaping the url by using raw on the entire url like so:
<%= link_to "link", raw(gateway_index_url(developer:#item.developer.api_key, tracker:"email", url:#product.url)) %>

How can I troubleshoot this JSON method in DataTables gem?

I'm trying to implement the Railscast 340 that demos how to use DataTables, which looks like an awesome gem for my project.
My model is different, of course; but the datatables class the Mr Bates builds (very quickly), in order to do server-side processing, is rather complicated to follow. I got the source code, and basically attempted to follow along. My view comes up with zero records (but there are > 10,000 records), but does not break.
However, here is what the error message output from the rails server says just before it stops:
NameError (undefined local variable or method `genotypes' for #<GenotypesDatatable:0xa9e852c>):
app/datatables/genotypes_datatable.rb:12:in `as_json'
app/controllers/genotypes_controller.rb:8:in `block (2 levels) in index'
app/controllers/genotypes_controller.rb:6:in `index'
Just before this, there appears to be this JSON error, which starts:
Started GET "/genotypes.json?sEcho=1&iColumns=8&sColumns=&iDisplayStart=0&iDisplayLength=10&mDataProp_0=...
The relevant part of the genotypes controller looks like this:
def index
respond_to do |format|
format.html
format.json { render json: GenotypesDatatable.new(view_context) }
end
end
And my genotypes model looks like:
class Genotype < ActiveRecord::Base
attr_accessible :allele1, :allele2, :run_date
belongs_to :gmarkers
belongs_to :gsamples
end
My datatables class is given below. This is from Mr Bates code, modified (most likely incorrectly) to replace his Products model with my Genotypes model:
class GenotypesDatatable
delegate :params, :h, :link_to, to: :#view
def initialize(view)
#view = view
end
def as_json(options = {})
{
sEcho: params[:sEcho].to_i,
iTotalRecords: Genotype.count,
iTotalDisplayRecords: genotypes.total_entries,
aaData: data
}
end
private
def data
genotypes.map do |genotype|
[
link_to(genotype.name, genotype),
h(genotype.category),
h(genotype.released_on.strftime("%B %e, %Y")),
genotype.run_date
]
end
end
def Genotypes
#Genotypes ||= fetch_Genotypes
end
def fetch_genotypes
genotypes = Genotype.order("#{sort_column} #{sort_direction}")
genotypes = genotypes.page(page).per_page(per_page)
if params[:sSearch].present?
genotypes = genotypes.where("name like :search or category like :search", search: "%#{params[:sSearch]}%")
end
genotypes
end
def page
params[:iDisplayStart].to_i/per_page + 1
end
def per_page
params[:iDisplayLength].to_i > 0 ? params[:iDisplayLength].to_i : 10
end
def sort_column
columns = %w[gmarker gsample allele1 allele2 run_date]
columns[params[:iSortCol_0].to_i]
end
def sort_direction
params[:sSortDir_0] == "desc" ? "desc" : "asc"
end
end
Any hints on how to troubleshoot (or fix!) this error much appreciated! (Getting this working for my project would be awesome!)
TIA,
rixter
I'm not sure if this is it, but your class has a Genotype method with capital G, it should be all lowercase.

Rails 3 - routing and parameterized name

I use this rule in my model:
def to_param
"#{self.name.parameterize}"
end
and in my helper:
def articles_menu
menu = '<ul>'
Article.all.each do |article|
menu += '<li>'
menu += link_to "#{article.name}", article
menu += '</li>'
end
menu += '</ul>'
return menu.html_safe
end
but when I'll go to the /articles/my-new-flat, I'll get the error
ActiveRecord::RecordNotFound in ArticlesController#show
Couldn't find Article with id=my-new-flat
Missing I something else yet or is any problem in my app? I though for parameterizing of the name is needed only set up in the model the rule...
Use FriendlyId gem it has all what you need, here is the link https://github.com/norman/friendly_id/blob/master/README.md
Problem with your code is that rails under the hub is trying to query your model by "id" attribute, it is not querying "name" attribute. FriendlyId gem patches this for models you want

Rails current_page? "fails" when method is POST

I have a really simple problem. I have a page of reports and each report has its own tab. I'm using current_page? to determine which tab should be highlighted. When I submit any report, current_page? doesn't seem to work anymore, apparently because the request method is POST.
Is this the intended behavior of current_page? I have a hard time imagining why that would be the case. If it is, how do people normally get around this problem?
Here's an example of a current_page? call:
<li><%= link_to "Client Retention", reports_client_retention_path, :class => current_page?(reports_client_retention_path) ? "current" : "" %></li>
All right, it looks like I figured out the answer to my own question about 5 minutes after putting up a bounty. It looks like current_page? will always return false on POST.
Here's the source code for current_page?:
# File actionpack/lib/action_view/helpers/url_helper.rb, line 588
def current_page?(options)
unless request
raise "You cannot use helpers that need to determine the current " "page unless your view context provides a Request object " "in a #request method"
end
return false unless request.get?
url_string = url_for(options)
# We ignore any extra parameters in the request_uri if the
# submitted url doesn't have any either. This lets the function
# work with things like ?order=asc
if url_string.index("?")
request_uri = request.fullpath
else
request_uri = request.path
end
if url_string =~ %r^\w+:\/\//
url_string == "#{request.protocol}#{request.host_with_port}#{request_uri}"
else
url_string == request_uri
end
end
I don't really understand why they would have gone out of their way to make current_page? work only for GET requests, but at least now I know that that's the way it is.
You could create a new current_path? method in your ApplicationHelper:
def current_path?(*paths)
return true if paths.include?(request.path)
false
end
Pass in one or more paths and it returns true if any match the user's current path:
current_path?('/user/new')
current_path?(root_path)
current_path?(new_user_path, users_path '/foo/bar')
Or, you can create a new current_request? helper method to check the Rails controller + action:
def current_request?(*requests)
return true if requests.include?({
controller: controller.controller_name,
action: controller.action_name
})
false
end
Pass in one or more controller + action and it returns true if any match the user's current request:
current_request?(controller: 'users', action: 'new')
current_request?({controller: 'users', action: 'new'}, {controller: 'users', action: 'create'})
==UPDATE==
Ok, I decided to make using current_request? a little less verbose by not requiring that you type out the controller when you are trying to match multiple actions:
def current_request?(*requests)
requests.each do |request|
if request[:controller] == controller.controller_name
return true if request[:action].is_a?(Array) && request[:action].include?(controller.action_name)
return true if request[:action] == controller.action_name
end
end
false
end
Now you can do this:
current_request?(controller: 'users', action: ['new', 'create'])
I was having the same problem when using POST. My solution was to do something like this
def menu_item link_text, link_path
link_class = (request.original_url.end_with? link_path) ? 'active' : ''
content_tag :li, link_to(link_text, link_path), class: link_class
end
where link_path is just url_for(action: 'action', controller: 'controller')