Default form values in Rails

One of the problems I initially ran into using Rails was the problem of how the hell you set initial values for your forms? (For example a select menu with a default value chosen but which a user can change). It turns out that as long as you don’t try and set the values in your views, it’s easy and there are several solutions.

As an example I started off with a classic Post model, then moved on to Ghost and Roast to try out alternatives (well you’ve got to call your models something…) I generated an identical scaffold for each and then ran a migration e.g.

 
rails generate scaffold Post name:string title:string type_id:integer
 
rake db:migrate

1. Use model after_initialize

/app/models/post.rb

1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
 
class Post < ActiveRecord::Base
  attr_accessible :name, :title, :type_id
  validates :name,  :presence => true
 
  after_initialize :init
 
  private
    def init
      if self.new_record? && self.type_id.nil?
        self.type_id = 5
      end
    end
 
end

Edit the model and add an after_initialize callback. This callback is called after a new object is instantiated. The init method sets the default value, but only if the value has not been set yet.

http://api.rubyonrails.org/classes/ActiveRecord/Callbacks.html

2. Set the default in the controller

/app/controllers/ghosts_controller.rb

1
2
3
4
5
6
7
8
9
10
  # GET /ghosts/new
  # GET /ghosts/new.json
  def new
    @ghost = Ghost.new
 
    respond_to do |format|
      format.html # new.html.erb
      format.json { render :json => @ghost }
    end
  end

Using this alternative solution, you simply set the default value in the new method using @ghost.type_id = 5. This value will only ever be set before the new view for this controller is created.

1
2
3
4
5
6
7
8
9
10
11
  # GET /ghosts/new
  # GET /ghosts/new.json
  def new
    @ghost = Ghost.new
    @ghost.type_id = 5
 
    respond_to do |format|
      format.html # new.html.erb
      format.json { render :json => @ghost }
    end
  end

This solution is easy implement and has the advantage that what you are doing is obvious – the default isn’t tucked away where you might forget about it.

3. Set the default in the database

When the rails generate command was run, a migration was automatically created:

/db/migrate/20130209234708_create_roasts.rb

1
2
3
4
5
6
7
8
9
10
class CreateRoasts < ActiveRecord::Migration
  def change
    create_table :roasts do |t|
      t.string :name
      t.string :title
      t.integer :type_id
      t.timestamps
    end
  end
end

We can edit the migration to set a default value here e.g.

1
2
3
4
5
6
7
8
9
10
class CreateRoasts < ActiveRecord::Migration
  def change
    create_table :roasts do |t|
      t.string :name
      t.string :title
      t.integer :type_id, :default => 5
      t.timestamps
    end
  end
end

Conclusion

Here are three ways of setting the default values. What you choose to do is up to you, I think it is important that a solution is consistent with the rest of the code that you are working with (as long as it isn’t bad code). Maintainability and clarity shouldn’t be neglected and I subscribe to the school of thought that you should always keep things simple – when complicated problems crop up, write complicated solutions, but don’t complicate things for the sake of it.

Personally I would be disinclined to use the final method because I think it would be easy to forget about.

Creating a method in the model may be overkill most of the time, but if you are setting a lot of default values or your default values change with context, then setting the default values in the method makes sense to me.

These code examples were built with Ruby on Rails 3.2.9

Sinatra templates from params

Having been playing about with Sinatra I’m finding it cropping up in all kinds of useful ways. I shouldn’t be too surprised though, as that is the whole raison d’etre of micro-frameworks.

When I get around to it I am writing a little Sinatra app, but for me it has a found a real niche helping to prototype or mess around with CSS and Javascript – it only takes a few seconds to create a little app to play around with.

Here is a minimal app.rb file. It will load templates from the (default) /views directory based on the :name parameter.

1
2
3
4
5
6
7
8
9
10
11
 
require 'rubygems'
require 'sinatra'
 
get '/' do
    erb :index
end
 
get '/map/:name' do
    erb params[:name].to_sym
end

The key here is to_sym – this is not Sinatra specific it is part of the Ruby language. to_sym converts a string into a symbol.

If the concept of a symbol is a little woolly read this for an excellent explanation. An easy (although probably incorrect or simplistic) is to think of a ruby symbol simply as an immutable name for something that can either be a string or an integer. Once created it cannot change.

WordPress updates with SFTP

A lot of people seem to have a great deal of difficulty using the WordPress update facility that allows you to update your WordPress install, themes and plugins from within the WordPress admin. As is so often the case, file and directory permissions are often to blame. (Updating WordPress in the Codex is worth reading)

Update WordPress

If you are using shared hosting with a company like Dreamhost (for example), then you are in luck. If you are managing your own server or are on many other hosts, then you may have a great deal of difficulty.

I’ve recently given the blog associated with one of the sites I manage a bit of a makeover. The site has a dedicated server so we can do what we want. We’ve always had SFTP accounts no basic FTP access. Historically the blog was hosted in a sub directory of the main site and the theme shared many files with the main site and had access to the main site database.

The reason it is important to use SFTP is that FTP user names and passwords are sent as plain text and can be captured by a third party using the same network. SFTP is a secure extension to SSH that allows you to carry out FTP actions.

We decided to unwind this relationship for a variety of reasons (security and ease of maintenance being key) and move the blog into it’s own sub domain.

I wanted to have the facility to just click the update button and have WordPress update automatically rather than have the hassle of applying all the updates manually. In-fact I think that one of the reasons there are so many insecure WordPress installations is that manually updating the core and the plugins can be very time consuming.
I really had no idea that getting WordPress to update from the admin using SFTP would take me so long. I even ended up pokeing around in the code to see what was going on…

Eventually I found the SSH SFTP Updater Support plugin which works like a dream. I think it’s quite odd this isn’t built in, especially as keeping code up-to-date is so important.

Update your WordPress with SFTP

Don’t forget to include the SFTP/SSH port 22 on the end of the hostname.

Keep a website looking good

We all know the story.

A new website looks beautiful… but not for long

A year later, the owners of the website go out looking for a new website because their once gorgeous website now looks terrible.

What has happened?

The code hasn’t changed but the content has. As developers or designers we often fail to appreciate how hard it can be for non web people (usually the owners) to manage their content.

When developers hand over websites to clients they are always tweaked to look perfect, if the content doesn’t quite fit the design, the content can be amended. If you have just built and populated a website it is very easy to add quickly add a couple of new styles, it is not so easy for most people.

Most people are not stupid; most business owners are not stupid – the problem is simply that most people have never had any visual training, nobody has ever sat down and given them any tips.

As a result, despite having the best of intentions, websites (and most printed material that hasn’t been produced by a designer) tend to end up as a bit of a mess. Technology like WYSIWYG editors, user friendly web applications and easy to use desktop programmes have made content creation accessible to huge numbers of people, but they have also made it very easy to make an incredible mess.

A few useful  guidelines

There are a few guiding principles to making the content, specifically the copy of a website look good:

  • Keep it simple & consistent.
  • Choose a few colours that are easy to read, and which are appropriate for the design of the website.
  • Choose your fonts carefully and stick to them. It is common practice now to choose a body font that is easy to read (e.g. Arial) and then choose a webfont for headings to provide visual interest.
  • Don’t use go crazy with all the different font sizes and variants. Use elements like sub-headings, blockquotes and one or two nicely crafted styles (e.g. a wrapping a paragraph in a keyline)
  • Use images to break up the flow of text, but make sure they enhance and are complementary to the text (and For emphasis don’t forget the alt tags)
  • Think about floating elements like images or videos so that the text wraps around to add further interest and provide a flow to the page.

What we can do to help

A lot companies have style guides and brand guidelines that they use to help maintain consistent printed material. I’m always amazed how few companies do the same thing to help manage their online presence. You should produce a style guide in conjunction with the website visuals. Having a guide to follow makes the business of inputting or updating great swathes of content much easier.

A PDF of the guide is often useful but why not just create a private page within the CMS that gives the user examples of what they can do? Here are some of the things I include:

  • Show the headings and sub headings and give examples of how you would use them.
  • Give examples of lists
  • Show images displayed block, floated left and floated right
  • Show images with captions displayed block, floated left and floated right
  • Give an example of a blockquote and cite, with an explanation of when to use them
  • Even after you have formally handed over a site do a bit of hand holding – being nice to clients usually pays dividends.

Here’s one I prepared earlier…

This is a style guide that is part of another WordPress site. Feel free to copy and use as a basis.

Screenshot of a style guide
Screenshot of a style guide page created for a WordPress site.

Code for a WordPress style demo page

1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
59
60
61
62
63
64
65
66
67
68
69
70
71
72
73
74
75
76
77
78
79
80
This is a style guide to demonstrate how you can style up the text on your website. Try to make your website interesting and easy to read. Break content up into small chunks. Add visual interest with lists and images.
<h1>This is an H1 tag.</h1>
Do not use the H1 ever, we generate them automatically from the page title.
<h2>This is a H2 tag.</h2>
Use this for sub headings on a page.
<h3>This is an H3 tag.</h3>
Use this for for further headings. <strong>This is bold text.</strong> <big>This is some text in a <big> tag</big> Use the <big> tag for emphasis e.g. to highlight the first paragraph on the page. <em>This is italic text.</em>
</big></big>
<h2>This is a paragraph with an image floated to the left.</h2>
<img class="alignleft size-medium wp-image-1231" alt="Luminous" src="/wp-content/uploads/2013/01/luminous_1-300x193.jpg" width="300" height="193" />Lorem ipsum dolor sit amet, consectetur adipiscing elit. Aenean a ante ligula, ut hendrerit odio. Donec posuere felis vel velit feugiat eu euismod dolor aliquam. Vestibulum fringilla posuere nisi. Lorem ipsum dolor sit amet, consectetur adipiscing elit. Sed tincidunt posuere tristique. Nam elementum convallis elementum. Aenean in arcu commodo quam tempor tempus. Pellentesque habitant morbi tristique senectus et netus et malesuada fames ac turpis egestas. Fusce ac ipsum et quam porta molestie. Nunc ac erat velit, eget convallis nisi. Donec quis eros ut dui hendrerit accumsan. Lorem ipsum dolor sit amet, consectetur adipiscing elit. Aenean a ante ligula, ut hendrerit odio. Donec posuere felis vel velit feugiat eu euismod dolor aliquam. Vestibulum fringilla posuere nisi. Lorem ipsum dolor sit amet, consectetur adipiscing elit. Sed tincidunt posuere tristique. Nam elementum convallis elementum. Aenean in arcu commodo quam tempor tempus. Pellentesque habitant morbi tristique senectus et netus et malesuada fames ac turpis egestas. Fusce ac ipsum et quam porta molestie. Nunc ac erat velit, eget convallis nisi. Donec quis eros ut dui hendrerit accumsan.
<h2>This is a paragraph with an image floated to the right.</h2>
<img class="alignright size-medium wp-image-1231" alt="Luminous" src="/wp-content/uploads/2013/01/luminous_1-300x193.jpg" width="300" height="193" />Lorem ipsum dolor sit amet, consectetur adipiscing elit. Aenean a ante ligula, ut hendrerit odio. Donec posuere felis vel velit feugiat eu euismod dolor aliquam. Vestibulum fringilla posuere nisi. Lorem ipsum dolor sit amet, consectetur adipiscing elit. Sed tincidunt posuere tristique. Nam elementum convallis elementum. Aenean in arcu commodo quam tempor tempus. Pellentesque habitant morbi tristique senectus et netus et malesuada fames ac turpis egestas. Fusce ac ipsum et quam porta molestie. Nunc ac erat velit, eget convallis nisi. Donec quis eros ut dui hendrerit accumsan. Lorem ipsum dolor sit amet, consectetur adipiscing elit. Aenean a ante ligula, ut hendrerit odio. Donec posuere felis vel velit feugiat eu euismod dolor aliquam. Vestibulum fringilla posuere nisi. Lorem ipsum dolor sit amet, consectetur adipiscing elit. Sed tincidunt posuere tristique. Nam elementum convallis elementum. Aenean in arcu commodo quam tempor tempus. Pellentesque habitant morbi tristique senectus et netus et malesuada fames ac turpis egestas. Fusce ac ipsum et quam porta molestie. Nunc ac erat velit, eget convallis nisi. Donec quis eros ut dui hendrerit accumsan.
<h2>This is a paragraph with an image floated to the left the image has a caption.</h2>
[caption id="attachment_854" align="alignleft" width="300"]<img class="size-medium wp-image-1231" alt="Luminous" src="/wp-content/uploads/2013/01/luminous_1-300x193.jpg" width="300" height="193" /> This is a caption to this image[/caption]
 
Lorem ipsum dolor sit amet, consectetur adipiscing elit. Aenean a ante ligula, ut hendrerit odio. Donec posuere felis vel velit feugiat eu euismod dolor aliquam. Vestibulum fringilla posuere nisi. Lorem ipsum dolor sit amet, consectetur adipiscing elit. Sed tincidunt posuere tristique. Nam elementum convallis elementum. Aenean in arcu commodo quam tempor tempus. Pellentesque habitant morbi tristique senectus et netus et malesuada fames ac turpis egestas. Fusce ac ipsum et quam porta molestie. Nunc ac erat velit, eget convallis nisi. Donec quis eros ut dui hendrerit accumsan. Lorem ipsum dolor sit amet, consectetur adipiscing elit. Aenean a ante ligula, ut hendrerit odio. Donec posuere felis vel velit feugiat eu euismod dolor aliquam. Vestibulum fringilla posuere nisi. Lorem ipsum dolor sit amet, consectetur adipiscing elit. Sed tincidunt posuere tristique. Nam elementum convallis elementum. Aenean in arcu commodo quam tempor tempus. Pellentesque habitant morbi tristique senectus et netus et malesuada fames ac turpis egestas. Fusce ac ipsum et quam porta molestie. Nunc ac erat velit, eget convallis nisi. Donec quis eros ut dui hendrerit accumsan.
<h2>These are lists.</h2>
Try and break up your content into short snappy bite sized pieces use lists frequently. They add interest to your page and let you highlight key points.
<ul>
<ul>
	<li>Lorem ipsum dolor sit amet, consectetur adipiscing elit.</li>
</ul>
</ul>
&nbsp;
<ul>
	<li>Aenean a ante ligula, ut hendrerit odio.</li>
</ul>
&nbsp;
 
&nbsp;
<ul>
	<li>Donec posuere felis vel velit feugiat eu euismod dolor aliquam.</li>
</ul>
&nbsp;
 
&nbsp;
<ul>
	<li>Vestibulum fringilla posuere nisi.</li>
</ul>
&nbsp;
 
&nbsp;
<ol>
<ol>
	<li>Lorem ipsum dolor sit amet, consectetur adipiscing elit.</li>
</ol>
</ol>
&nbsp;
<ul>
	<li>Sed tincidunt posuere tristique.</li>
</ul>
&nbsp;
 
&nbsp;
<ul>
	<li>Nam elementum convallis elementum.</li>
</ul>
&nbsp;
 
&nbsp;
<ul>
	<li>Aenean in arcu commodo quam tempor tempus.</li>
</ul>
&nbsp;
 
&nbsp;
 
&nbsp;
<h2>This is a blockquote</h2>
Use this to highlight things like quotes, testimonials or key points.
<blockquote>Lorem ipsum dolor sit amet, consectetur adipiscing elit. Aenean a ante ligula, ut hendrerit odio. Donec posuere felis vel velit feugiat eu euismod dolor aliquam. Vestibulum fringilla posuere nisi. Lorem ipsum dolor sit amet, consectetur adipiscing elit. Sed tincidunt posuere tristique. Nam elementum convallis elementum. Aenean in arcu commodo quam tempor tempus. Pellentesque habitant morbi tristique senectus et netus et malesuada fames ac turpis egestas. Fusce ac ipsum et quam porta molestie. Nunc ac erat velit, eget convallis nisi. Donec quis eros ut dui hendrerit accumsan.</blockquote>
This is an
 
<hr />
 
tag. Use this split up blocks of content.
 
<hr />
 
Lorem ipsum dolor sit amet, consectetur adipiscing elit. Aenean a ante ligula, ut hendrerit odio. Donec posuere felis vel velit feugiat eu euismod dolor aliquam. Vestibulum fringilla posuere nisi. Lorem ipsum dolor sit amet, consectetur adipiscing elit. Sed tincidunt posuere tristique. Nam elementum convallis elementum. Aenean in arcu commodo quam tempor tempus. Pellentesque habitant morbi tristique senectus et netus et malesuada fames ac turpis egestas. Fusce ac ipsum et quam porta molestie. Nunc ac erat velit, eget convallis nisi. Donec quis eros ut dui hendrerit accumsan.