Showing posts with label views. Show all posts
Showing posts with label views. Show all posts

Thursday, 21 July 2011

meta_search sort_link helper and associations

It took me a while to find this, so, for my own memory I am going to quickly write this up.

I have a view that shows a table of objects (a pretty standard index view). The only issue was I want to sort on one of the columns that actually has data coming not from the main object but an association.
What I discovered is a line in a posting here that says:

You can define your own custom sort scopes. Define scopes named “sort_by__asc” and “sort_by__desc” and sort_link @search, :name will work as you might expect.

So, I have an object of 'info' defined like this:
class Info < ActiveRecord::Base
belongs_to :region
scope :contains_string, lambda {|str| where(:name.matches % "%#{str}%")}
search_methods :contains_string

scope :active, lambda{where(:active => true)}
search_methods :active, :type => :boolean
end


What I found is that you can put this at the end:
scope :sort_by_region_name, lambda{joins(:region).order("regions.name asc")}
search_methods :sort_by_region_name


and then in my view I can do:

<table>
<thead>
<tr>
<td width="25%"><%= sort_link @info_search, :name, "Info" %></td>
<td width="25%"><%= sort_link @info_search, :region_name, "Region" %></td>
<td><%= sort_link @info_search, :active %></td>
</tr>
</thead>
...body info...
</table


And in my controller:
class Admin::InfosController < Admin::BaseController
def index
search = params[:search] || {"meta_sort" => "name.asc"}

@info_search = Info.search(search)
@infos = @linfo_search.paginate(:page => params[:page]||1, :per_page => 15) # load all matching records
end
end


And presto I have an index that
a) default to sorting by name (see the first line of the index method)
b) let's me sort on an associated value

Cool!

Sunday, 24 May 2009

Forcing a different render format

I am writing an OAuth system for FilmAmora for the iphone app (and anything else I guess) to use.
I want to always output xml from the controller that is handling the catalog output... but how to do that!

I came up with this:

  def list
render :template => "/catalogs/list.xml.builder", :content_type => "text/xml"
end


This will always output xml (with the right mime type) no matter what the requested format was.

Monday, 8 December 2008

checkboxes for multiple items

I am doing an interface where I want to list a bunch of things (index) and have a checkbox next to each of them. Then, using a button, edit or show all those selected items.
I am always running into this problem of checkboxes (maybe I am just stupid) so I spent some time and figured out a way that works for me. There are probably other solutions, but here is what I do:

First, in the index.html I have this javascript code:

<% content_for :javascript do %>
<script type="text/javascript" charset="utf-8">
/* <![CDATA[ */
function editDevices() {
var device_count = document.getElementsByName('device[]').length;
var total="";
for(var i=0; i < device_count; i++){
if(document.forms['group_edit'].elements['device[]'][i].checked) {
if (total.length > 0) {
total += ","
}
total +=document.forms['group_edit'].elements['device[]'][i].value;
}
}

new Ajax.Request('<%= group_edit_devices_path %>', {
parameters: {
authenticity_token: encodeURIComponent('<%=form_authenticity_token%>'),
device_ids: total
}
}
);
}

function showDevices() {
var device_count = document.getElementsByName('device[]').length;
var total="";
for(var i=0; i < device_count; i++){
if(document.forms['group_edit'].elements['device[]'][i].checked) {
if (total.length > 0) {
total += ","
}
total +=document.forms['group_edit'].elements['device[]'][i].value;
}
}

new Ajax.Request('<%= group_show_devices_path %>', {
parameters: {
authenticity_token: encodeURIComponent('<%=form_authenticity_token%>'),
device_ids: total
}
}
);
}
/* ]]> */
</script>
<% end %>


Then I have the table of devices:

<table border="0" cellspacing="5" cellpadding="5">
<thead>
<tr>
<th>&nbsp;</th>
<th>Uid</th>
<th>Name</th>
<th>Ip</th>
<th># Displays</th>
</tr>
</thead>
<tfoot>
<tr>
<td colspan="5">
<ul class="tabs">
<li><%= link_to_function "Show", "showDevices()" %></li>
<li><%= link_to_function "Edit", "editDevices()" %></li>
<li><%= link_to "Delete" %></li>
</ul>
</td>
</tr>
</tfoot>
<tbody>
<% for device in @devices %>
<tr>
<td><%= check_box_tag("device[]", device.id, false, :id => "device_#{device.id}") %></td>
<td><%=link_to_remote h(device.uid), :url => formatted_device_path(device, :js), :method => "get" %></td>
<td><%=h device.name %></td>
<td><%=h device.ip %></td>
<td><%= device.displays.count %></td>
</tr>
<% end %>
</tbody>
</table>


The result is that my ajax function will be called with a comma separated list of the ids of the selected devices.

Friday, 15 August 2008

secure forms

One thing I struggled with in RoR was creating forms that submitted to https. So I ended up writing a couple of helpers:

  def secure_form_for(record_or_name_or_array, *args, &proc)
unless RAILS_ENV == 'production'
url_options = {}
else
url_options = {:protocol => 'https://', :only_path => false }
end

options = args.last.is_a?(Hash) ? args.pop : {}
if !options[:url].nil?
options[:url] = url_options.merge options[:url]
else
options[:url] = url_options
end

return form_for(record_or_name_or_array, options, &proc)
end


and

  def secure_form_tag(*args, &proc)
logger.debug("secure_form_tag args #{args.inspect}")
unless RAILS_ENV == 'production'
url_options = {}
else
url_options = {:protocol => 'https://', :only_path => false }
end

options = args.last.is_a?(Hash) ? args.pop : {}
if !options[:url].nil?
options[:url] = url_options.merge options[:url]
else
options[:url] = url_options
end

logger.debug("secure_form_tag options #{options.inspect}")

return form_tag(options, &proc)
end


The should be simple replacements for form_for and form_tag. Now, I have to admit I wrote these when I was using Rails 1.2.5, so there might be some things in 2.x that make these redundant, but, they work for me.
The only caveat is that if you are doing a form where you are not passing in the action, just the object e.g

<% form_for @object do %>


Then you are going to have to supply the actions. I am looking into this now, and I might rewrite this post if I sort it out!

Sunday, 20 July 2008

Escaping for JavaScript

Recently I've started to use the most excellent Prototip2 for doing sexy tooltip stuff. It works a treat.
The only problem I have had is that some of the things I want to put into the tips have single quotes in them (e.g Bob's Team). I was surprised to find that Rails doesn't (as far as I could find) have a handy dandy way of making strings JS friendly. So I whipped up this extention to Erb::Util.
I hope some of you find it useful. It will escape single quotes and as an added bonus it also does the html escaping so you only have to make one call.

class ERB
module Util
def js_escape(str)
h(str.gsub(/[']/, '\\\\\''))
end

alias js js_escape
module_function :js
module_function :js_escape
end
end


I put this into an initializer.

You can then call it from your views like this:

<%=js team.name%>

Thursday, 19 June 2008

IE and form spacing

One has to wonder how Microsoft got it so wrong, but anyway.

One thing I love about RoR is the ajax side of it and how easy it makes it. For instance adding something to a cart with ajax:

<% form_remote_tag :url => {:controller => :store, :action => :add_to_cart, :id => film} do %>
<%=submit_tag(_('Buy &raquo;'), "title" => _("add to cart @ %s") % number_to_currency(film.price, :unit => "€"), :class => "buy_button_big buy_button")%>
<% end %>



That is great. On FireFox it looks like this:


But on IE6 it looks like this:


Insane quatities of extra space. Seems that IE loves to add space after forms. You can't stop it!

Or can you!?

I have found that adding this in my css is the trick:

form {
margin:0;
padding:0;
}


But, since I don't need it in ff... why not use the very sweet CSS Browser Selector plugin.

Now you can do this:

.ie6 form {
margin:0;
padding:0;
}


Add all shall be well in the garden.

Saturday, 14 June 2008

Absolving your views of responsibility

One thing I struggled with when I started out with RoR was how to create a site that was 'current looking'. In all the books they told you about views and layouts, but not how to use the layout to its most effective end.
What I wanted was a simple 3 column website. But instead of 'static' information in the left and right column I wanted it to change. In some cases it was ads, in some cases a list of items, etc. The only thing I could think of was to hold a lot of layout information in the view. So, I would have the header and footer in layouts/application.html.erb but in the middle there was a big <%= :yield %> that would handle the middle (vertically) of the page, including the columns.
(Hold on, I'm getting to the code!)
The problem with this is that if your view is wrong, or if you don't include it, then your site goes all to hell.

The solution, I found, was named :yields.

To illustrate I am going to build a funky 3 column site in 5 minutes.

Create the project

$ rails threecol


To set up a new project

Neat tip: open TextMate and drag the threecol folder onto the icon in the doc. That way it will open up the whole structure (i.e. the rails project).

Add a layout

Matthew James Taylor has a great website with some free to use CSS templates. So, we're going to use his 3 column one.

Go here. View source, copy the CSS.

Create a new file in your public/stylesheets directory called site.css and paste the CSS from Matt's page in.

Include the CSS in your Layout

Create a file in your app/views/layouts directory called application.html.erb. This is the name for the default layout, so you don't need to change anything in the controller we'll create in a moment.

Go back to Matt's page, view source and paste the whole thing into application.html.erb. Delete the styles definitions from here. (lines 12 - 170 as of this writing)

Knock up a scaffold

(Best to setup the database.yml here first)

$ script/generate scaffold product name:string description:string


note: in Rails 2 you don't have the same scaffolding as before. doing the above, where you define some fields, will give you a controller, model, views and migration

Get everything setup:

$ rake db:drop db:create db:migrate test


Get your CSS on

Delete products.html.erb from the layouts directory. For our example we don't need it.

Back in your application.html.erb paste this line in the header:

<%= stylesheet_link_tag 'site' %>


If you start the server (script/server) now and go to localhost:3000/products you should see Matthew's page all nice and purty because we haven't included any of our content.

Get your content in

Delete the center of Matthew's code (lines 40 - 59 here) and replace it with

<%= :yield %>


Refresh now and you will see your scaffold in the middle. Nice.

Sidebars

Ok, we could have done all that easy, so let's get to the fun stuff.
Delete Matthew's code for either sidebar.
The center of your application.html.erb should now look like this:

            <div class="col1">

<!-- Column 1 start -->
<%= yield %>
<!-- Column 1 end -->
</div>
<div class="col2">
<!-- Column 2 start -->
<!-- Column 2 end -->
</div>
<div class="col3">
<!-- Column 3 start -->
<!-- Column 3 end -->
</div>



inside column 2 (the left nav in Matthew's layout) put this:

<%= yield :left_nav_content %>


In views/products/index.html.erb do this:
<% content_for :left_nav_content do %>
<h1>Here it is!</h1>
<div>Exciting left-nav content</div>
<% end %>



What is going on?

We all know about <%= yield %>, but adding a name to it says to look in your view (or any views including, even through partial rendering) and see if there is something that wants to write out to this space. <% content_for :left_nav_content do %> says that the stuff in here, please write there.

The power is - you can do anything in there. Include partials, for instance.

The advantage is that now you can not screw up your layout. You can still put things whereever you want, but the layout is out of the view's hands.

I hope this is clear. It made a big difference to how I construct views!