Ruby on Rails
FAQ

This list of Frequently Asked Questions(FAQ) is divided into the following sections:

General #

What is the most recent version of Rails?

Rails 2.1 was released on June 01, 2008.

What new features are in Rails 2.0?

A quick discussion of the new features is available in the article: Rails 2.0: It’s done!

What bugs exist in Rails?

These two reports show some (not all) of the remaining issues that did not make it into Rails 1.1:

What is the license for Rails?

See License.

Why the name “Rails”?

R for Ruby, a play on Struts, and I liked the sound of it ;).

How long has Rails been around?

Although not released until the 24th of July 2004, Rails has been in development since the Basecamp project started in mid/late 2003 (from http://www.loudthinking.com/arc/000446.html)

Is there a Rails book in the works?

There are a few! See the BookList.

How big is the rails code base?

See RailsStatistics.

return to top

What about a plugin system?

See Plugins (as of Rails 0.14)

Which version of Ruby should I use for Rails?

Ruby 1.8.4 is recommended.

To check your Ruby version type…

> ruby --version 

Web Servers #

What web server can I use with Rails?

Apache and Lighttpd are the most popular web servers for running Rails. But any web server that supports mod_ruby (Apache), CGI, SCGI, or FastCGI? can be used.

Apache is the reference web server and will be the one upon which all examples are based.

You may also want to consider using Lighttpd which is comparable in speed to Apache 2.0.54 using MPM Worker on Debian 3.1—this is considerably faster than Apache 1.x or 2.x MPM Prefork. WARNING: Lighttpd-1.4.10 is very buggy—use Lighttpd-1.4.11 or newer version.

A newer option is to use Zed Shaw’s Mongrel . Mongrel is a ruby based webserver that uses C extensions to dramatically improve performance compared to Webrick. Mongrel can be run independently or in a cluster behind a Lighttpd or Apache proxy.

Which is preferred, mod_ruby, SCGI or FastCGI??

We’ll divide the answer in 2 parts (FastCGI and non-FastCGI).

For FastCGI:

NOTE: mod_fcgid is very active and mod_fastcgi hasn’t been updated in years.

For non-FastCGI

When I’m using WEBrick to run Rails, is there a way to handle multiple sites on the same port, like you can with Apache and vhosts.conf?

Currently, no. Do have a look at hacking vendor/railties/webrick_server.rb if you want to give it a shot.

When I’m using WEBrick to run Rails, and running multiple Rails applications on different ports, I seem to be getting issues with cookies being shared across applications, causing errors. Is there a way around this?

Does Rails have something like PHP’s $_SERVER variable where you can access $_SERVER['HTTP_USER_AGENT'] and other details?

Rails has request.env, which is quite similar. See request.env in the API docs for more details (under the “Request” section)

Here’s also a list of VariablesInRequestEnv

I’m trying out rails on Windows with Webrick. I just created a controller called Interviews with script/new_controller. However, when I try to open <a href="http://localhost">http://localhost</a>:3000/interviews I get a Webrick 404 error. Is the URL rewriting not working in the webrick version? If not, how should I do it instead?

Make sure that you put a trailing slash after your controller, like http://localhost:3000/interviews/

I wish I didn’t have to add the trailing slash onto <a href="http://railsserver/somecontroller/">http://railsserver/somecontroller/</a> to access the index of somecontroller. Is there a way around this?

This happens automatically with Rails 0.6.0 (not yet with WEBrick, though).

How can I redirect the user back to the last action?

You can use redirect_to :back (which depends on request.env['HTTP_REFERER'] being available) or use session: @session[:return_to] = @request.request_uri from sender, then redirect_to @session[:return_to] on target.

Where do I put static files like images, stylesheets and javascripts?

Static files should go in the public folder. It is best to put images in public/images, stylsheets in public/stylesheets and javascripts in public/javascripts. This will allow you to use the built-in Helpers more effectively. In your rhtml, the url’s would be relative to public. Thus it’s /images/image.png not /public/images/images.png.

Where do I put my applications images, stylesheets and javascripts, etc. There’s a directory called public, but I think I read something about not putting files directly in this location, but just links to them. Oh, and what is the URL for them?

Rails previously used symlinks. Now it’s recommended that you just populate those real directories in public with your files. And then include the public directory in what you would check into CVS or Subversion.

return to top

Model-View-Controller (MVC)#

Why isn’t the session available to models?

The session is part of the controller layer, which sits above the model layer. While the controller layer relies on the model layer, the model layer should be independent from the controller layer.

But I need information from the session to implement business rules in my models. What do I do?

If there is a specific piece of information a model needs to implement some of its methods, the right approach is to provide an attr_accessor for that piece of information in the model. Controller code can then set that attribute on the model before using any methods that depend on it.

If you seem to need session information all over your models, you are probably trying to put controller code into your models; you should rethink your design.

Is there any reason not to store model objects in the session?

Yes, several good ones. You should only ever store a model’s id in the session. See sessions for such pitfalls and more information on the session in general. That said, there is a good workaround by François Beausoleil.

return to top

Associations #

What’s the difference between belongs_to and has_one?

The difference has to do with which table has the foreign key. See an illustration of ActiveRecordAssociations. For more details see the paragraph titled belongs_to or has_one from the API documentation.

If I have an association set up, say authors have many posts, what’s the correct way to create a new post from within the author?

@post = @author.post.build
@post.attributes = @params['post']
@post.save@

It will automatically fill the foreign key if it can. Of course @author has to exist in the db at this point.

return to top

Performance #

How can I reduce the number of repetitive queries being used in my Rails app.

As of Rails 0.12 most repetitive queries can be avoided by making use of EagerLoadingOfAssociations. See also PiggyBackQuery for an explanation of how to use your own SQL where appropriate.

What is the cost of Rails hitting the database to infer the properties of ActiveRecord objects? How often does this happen? Is this schema data ever cached? What other performance-related issues should I be aware of?

On CGI, everything reloads on every request. On FastCGI? and mod_ruby, AR will cache the column information.

As of Rails 0.12 See benchmarking and profiling scripts have been available. See BenchmarkSuiteWish for more details.

return to top

Other #

Why do helpers have you pass in the string for the instance variable, instead of the actual object?

Because I still need to names of the variables to properly construct the form element, so you’d quickly end up with a lot of input looking like text_field @post.title, "post", "title"—instead of just saying it once.

Is it possible to call a helper from the controller?

No, but you can move the helper method into the controller and add helper_method :method_name after the definition to make it available to the view again.


acyclovir, diflucan, ultram, valtrex, xenical acyclovir | diflucan | ultram | valtrex | xenical

How can I measure the size of my rails application?

Rake will report a number of statistics on your codebase

$ rake stats

How do I reverse a list in the view?

Given a situation where you have something like in your view:

<% @posts.each do |post| %>

The #each method can be replaced with #reverse_each which will traverse the array in reverse order.

<% @posts.reverse_each do |post| %>

How can I include an HTML class in a link using link_to ?

link_to "new", { :action => 'new' }, 'class' => 'inner'

See the API Docs for link_to for more details.

How do I prevent access to methods of a controller?

Make those methods private or protected.

When should I use singular or plural names?

See WhatGetsPluralized.

Why does Rails do pluralization?

see 10 reasons Rails does pluralization

Q. Is there any solid examples or documentation on using observers?

I couldn’t even get them working until I found this post:
http://www.loudthinking.com/arc/000362.html
and realized I needed to add something like observer :my_observer to the application.rb. Is that even the right place to put it??

If plain old “id” is deprecated, why is it used in Rails?

For normal ruby, id is deprecated in favour of object_id. For \ActiveRecord, id always does read_attribute(primary_key).

What statement is equivalent to <%= ... %>? render_text? printf?

concat(string, binding) can be used if needed. See the API docs for #concat in “ActionView::Helpers::TextHelper”

Do Rails sessions automatically fallback to GET-based session ID propagation if users choose to disable cookies?

No. That doesn’t mean it can’t be done.

(I’m still just getting started with Rails, but I’m thinking maybe this would be something you could use a filter for. The filter would scour the output for internal links and attach a session ID to the end of all of them. This ID might need to appear after a question mark in the URL so that stupid search engines that didn’t keep track of cookies wouldn’t think they were scouring different pages.)

How is -%> different from %> ?

The extra dash swallows the rest of the line (no newline in the output).

How is <%- different from <% ?

Apparently nobody knows.

How can I access the API docs offline? Are they available for download?

See OfflineDocumentation.

return to top

Database #

What database can I use with Rails?

See DatabaseDrivers. Many people prefer SQLite 3.x for development and either MySQL or PostgreSQL for production. Several others, including non-free commercial databases, are also supported by Rails.

How does access control to database tables and columns (fields) work in Rails?

ModelSecurity provides access control within the data model so you can specify read/write access for individual columns. It is a free, 3rd-party Rails Generator created by Bruce Perens which can easily be installed as a rubygem.

Problem: I have a field named the same as an AR class and its causing problems. What’s up?

Don’t give your fields the same name as any of your Active Record classes or tables. For instance don’t use flavor in your candies table, if Flavor descends from Active Record::Base. Use flavor_id (or anything other than flavor) instead.

How do I fix `No such file or directory – /tmp/mysql.sock` ?

See database.yml. You will most likely have to run `locate mysql.sock` or `locate mysqld.sock` to find where your socket is located, then update database.yml to reflect your system’s configuration.

Does Rails support mysql v5.0?

Yes it does. If you have login problems create a user and use the OLD_PASSWORD function to generate a compatible password. This is generally not a problem.

How should I store boolean values in the DB?

Use a tinyint(1). See HowtoUseBooleanColumns for more details.

Does ActiveRecord support ENUM column types?

No, not currently.

How do I fix Packets out of order with \MySQL 4.1

See MySQL Database access problem

What field names have special properties?

See MagicFieldNames.

When using SQLite I get this error. What’s wrong?


<a href="http://wiki.rubyonrails.com/rails/pages/ActiveRecord" class="existingWikiWord">ActiveRecord</a>::ConnectionFailed in Finance#list
undefined method `show_datatypes=' for #<SQLite::Database:0xf6dcf8f0>

As per directions in HowtoUseSQLite, make sure you are using sqlite-ruby and not sqlite from the gems. For me that was ‘2. sqlite-ruby 2.2.3 (ruby)’ on ‘gem install sqlite’.

NOTE: Use sqlite3-ruby (1.1.0) and SQLite 3.3.4 (or later) for best results.

Which ruby postgresql driver should I use?

There are 3, yes three, different postgresql drivers available for ruby (and rails).

1. postgres is old and stale but reliable
2. ruby-postgres is new and improving and beta
   it is essentially postgres + improvements
3. postgres-pr is pure ruby, slowest, runs anywhere

For rails 1.0 and 1.1, use ‘postgres’ or ‘postgres-pr’.

For rails 1.1.1 and beyond, try ‘ruby-postgres’ first to see if it works because that will be preferred in the future. You can always fall back to ‘postgres’ if it doesn’t work for you.

I use PostgreSQL. When I make inserts inside a transaction, calls to now() within SQL statements yield transaction-consistent timestampts (i.e. now() always returns the timestamp when the transaction started). I can still do this with AR by making an explicit UPDATE after saving, but is there any way to set AR date fields to some magic object that will result in now() being used in the INSERT statement generated by ActiveRecord::Base.save?

Within PostgreSQL, the CURRENT_TIMESTAMP family of functions returns the time of the start of the current transaction. The exception to this rule is the timeofday() function, which always returns the wall-clock time.

There was a thread on the mailing list about this,
From this thread, you can deduce that this is simply a misunderstanding about what PostgreSQL is supposed to do.

UPDATE: see ticket #4461 which provides a patch that is likely to be included with rails-1.1.1.

ActionMailer #

Is it somehow possible to enabled the ActionView helpers in my
ActionMailer classes? “url_for” seems not to be available in the
template (my application crashes because the method does not exist).

Currently, url_for is not accessible in mailer classes. The reason is
that url_for requires some infrastructure that is not available in
mailer classes. Until someone submits a patch that changes that, the
only way to take advantage of url_for in mailer classes is to do
something like :


   # in the controller
   url = url_for(...)
   SomeMailer.deliver_some_mail(url)

And then use the passed value to help render the mail.

Or alternatively check out:

http://wiki.rubyonrails.org/rails/pages/HowtoUseUrlHelpersWithActionMailer/

return to top


RJS #

When I use page.insert_html, some javascript is displayed in my page. How do I fix this?

I noticed this problem when I wrote a very small demo program using ajax and using the page.insert_html method.


--------- app/views/main/index.rhtml ------------
<h3>AJAX Demo</h3>

<ul id="my_list">
      <li>Original item... please add more!</li>
    </ul>
<% form_remote_tag (:update => 'my_list', 
          :position => 'top',
          :url => {:action => 'do_rjs_stuff'}) do -%>

</br>
<%= submit_tag "submit" %>
<% end %>

--- app/controllers/main_controller.rb --------
class MainController < ApplicationController

 def do_rjs_stuff
  render :update do |page|
    page.insert_html :before, 'my_list', "<li>" + "Bob"+ "</li>" 
  end 
 end

end
-----------------------------------------------

The problem turned out to be my use of :update
and :position in form_remote_tag. I guess
that because page.insert_html is already
specifying where the string should go (ie :before) it is wrong to put it in
form_remote_tag also. Hence I rewrote my view
to this:


<h3>AJAX Demo</h3>

<ul id="my_list">
      <li>Original item... please add more!</li>
    </ul>
<% form_remote_tag (:url => {:action => 'do_rjs_stuff'}) do -%>

</br>
<%= submit_tag "submit" %>
<% end %>

Now with this change the action worked as expected.


<% periodically_call_remote (...) %> doesn’t do anything. Why?

Answer: You need <%= periodically_call_remote (...) %> otherwise the relevant javascript code is not inserted into your html code.


Deprecated Features:

How is the deprecations page http://www.rubyonrails.org/deprecation useful in any sort of way? There is no actionable information listed! Where do we find useful information about deprecated features and how to migrate code to newer APIs. I’ve inherited a sprawling old rails 1.0.0 app that I have to migrate to 1.2.3.

Translations: