Top ruby-on-rails Questions

List of Tags

This post is from the early days of Stack Overflow, and while we recognize its historical significance, we also recognize that the current community of users will likely close similar posts. Please feel free to read and learn from this post, but refrain from creating similar posts just because this one exists.

I'm interested in learning a web framework. The two big ones, as I gather, are Rails and Django. Which one is better and/or faster? Is one better designed or more logically consistent than the other? Is there another framework I should look into? How easy is it to set up and administer a Rails or Django server, and how easy is it to find a shared hosting plan?

To give a little background, the websites I'm currently used to making are in straight PHP (no framework) and I'd like to be able to manage some of the complexity that comes from feature creep. Outputting HTML with echo becomes a lot less fun the more you have to customize it. In addition, I don't know either Ruby or Python so I'm free to go either way.

note: I'm not interested in ASP. I'd like to develop on a Mac and deploy to Linux/FreeBSD and I don't think that ASP fits the bill.


To everyone that's replied so far: thank you! Choosing a web framework can be a difficult thing, so I'll try to narrow down what I would like to do.

First, I would like to build small, custom sites (hard to call them "apps") that serve data from a database, and optionally an administrative interface to manage everything behind the scenes. As an example, I have a website for my grandmother to showcase her artwork built in PHP. I've spent more time on the backend than the front end to enable her to reorder, relabel, and reprice her artwork as well as upload an image, tag it, and have it scaled and appear on her site.

I notice both frameworks generate "scaffolding" that can be used as a rudimentary admin interface; how would they handle non-textual data (like images)?

Also, when watching a Rails screencast, there was a casual mention that the framework does some singular/plural translation. This strikes me as quite odd - is this what is referred to as "magic" in Rails? If so, does Django (or any other framework) have a more sensible naming strategy?

Answered By: Justin Lilly ( 178)

From my experiences, rails seemed to be more of a black box than django. You issue some command and some stuff happened and you got a basic CRUD application. You run this particular function and something happened and you got something else as an output, not knowing what the middle bits were. While this is fine for easy things, the lack of online documentation (in my experience) was a huge hindrance.

Django, on the other hand, seems to be more logical and transparent about what's going on behind the scenes. There's no "magic". Django is also one of the best documented open source projects out there.

Just came back and saw your additions:

If you want something with an extensible admin, pick Django. This is a test in which Django shines. Its clean looking and is extensible. In my experience, the Rails scaffolding is typically thrown away as you add more functionality. Its meant to get you up and going, but not necessarily something you'll see in production. That being said, lists for grandma aren't exactly production :) Reordering field and such is fairly easy, especially given the many community contributions to the admin.

When people talk about "magic" in Rails (or any other framework for that matter), they're really talking about things happening without it being immediately obvious why or how. A key example of this is Rails' find_by_* function. Its autocompleted function that you don't explicitly define, but its just "magically" there. You can find a lot more information at http://www.stephenbartholomew.co.uk/2007/6/4/is-rails-magic Purely antecdotal, but I've found that Python (and Django) itself is much more explicit where as Ruby (and Rails) rely a lot more on convention ("That's just the way its done.")

284
Jakub Arnold

How can I get the current absolute URL in my Ruby on Rails view?

The request.request_uri only returns the relative URL.

Answered By: Jaime Bellmyer ( 364)

For Rails 2: You want request.url instead of request.request_uri. This combines the protocol (usually http://) with the host, and request_uri to give you the full address.

For Rails 3: You want "#{request.protocol}#{request.host_with_port}#{request.fullpath}", since request.url is now deprecated.

I wrongly named a column hased_password instead of hashed_password.

How can I use a migration to rename this column?

Answered By: kwon ( 501)
rename_column :table, :old_column, :new_column

Update:

You'll probably want to create a separate migration to do this. (Rename FixColumnName as you will)

script/generate migration FixColumnName
# creates  db/migrate/xxxxxxxxxx_fix_column_name.rb

Then edit the migration to do your will.

# db/migrate/xxxxxxxxxx_fix_column_name.rb
class FixColumnName < ActiveRecord::Migration
  def self.up
    rename_column :table_name, :old_column, :new_column
  end

  def self.down
    # rename back if you need or do something else or do nothing
  end
end

An update for Rails 3.1

While, the up and down methods still apply. Rails 3.1 receives a change method that "knows how to migrate your database and reverse it when the migration is rolled back without the need to write a separate down method"

rails g migration FixColumnName

class FixColumnName < ActiveRecord::Migration
  def change
    rename_column :table_name, :old_column, :new_column
  end
end

If you happen to have a whole bunch of columns to rename, or something that would have required repeating the table name over and over again.

rename_column :table_name, :old_column1, :new_column1
rename_column :table_name, :old_column2, :new_column2
...

You could use change_table to keep things a little neater.

class FixColumnNames < ActiveRecord::Migration
  def change
    change_table :table_name do |t|
      t.rename :old_column1, :new_column1
      t.rename :old_column2, :new_column2
      ...
    end
  end
end

Thank you, Luke && Turadg, for bringing up the topic.


Then just db:migrate as usual or however you go about your business.

248
Ricardo Acras

I am running into some issues regarding Authenticity Token in rails, as I did many times now. But I really don't want to just solve this problem and go on, I would really like to understand Authenticity token. Well, my question is, do you have some complete source of information on this subject or would spend your time to explain in details here?

This is my last resource before going to the source code :-)

Answered By: Faisal ( 560)

What happens: When the user views a form to create, update, or destroy a resource, the rails app would create a random authenticity_token, store this token in the session, and place it in a hidden field in the form. When the user submits the form, rails would look for the authenticity_token, compare it to the one stored in the session, and if they match the request is allowed to continue.

Why this happens: Since the authenticity token is stored in the session, the client can not know its value. This prevents people from submitting forms to a rails app without viewing the form within that app itself. Imagine that you are using service A, you logged into the service and everything is ok. Now imagine that you went to use service B, and you saw a picture you like, and pressed on the picture to view a larger size of it. Now, if some evil code was there at service B, it might send a request to service A (which you are logged into), and ask to delete your account, by sending a request to http://serviceA.com/close_account. This is what is known as CSRF (Cross Site Request Forgery).

If service A is using authenticity tokens, this attack vector is no longer applicable, since the request from service B would not contain the correct authenticity token, and will not be allowed to continue.

Notes: Keep in mind, rails only checks POST, PUT, and DELETE requests. GET request are not checked for authenticity token. Why? because the HTTP specification states that GET requests should NOT create, alter, or destroy resources at the server, and the request should be idempotent (if you run the same command multiple times, you should get the same result every time).

Lessons: Use authenticity_token to protect your POST, PUT, and DELETE requests. Also make sure not to make any GET requests that could potentially modify resources on the server.

Edit: Check the comment by @erturne regarding GET requests being idempotent. He explains it in a better way than I have done here.

241
Ethan Gunderson

As it stands now, I'm a Java and C# developer. The more and more I look at Ruby on Rails, the more I really want to learn it.

What have you found to be the best route to learn RoR? Would it be easier to develop on Windows, or should I just run a virtual machine with Linux?

Is there an IDE that can match the robustness of Visual Studio? Any programs to develop that give a good overhead of what to do? Any good books?

Seriously, any tips/tricks/rants would be awesome.

Answered By: Jason Navarrete ( 205)

I've been moving from C# in my professional career to looking at Ruby and RoR in my personal life, and I've found linux to be slightly more appealing personally for development. Particularly now that I've started using git, the implementation is cleaner on linux.

Currently I'm dual booting and getting closer to running Ubuntu full time. I'm using gedit with various plugins for the development environment. And as of late 2010, I'm making the push to use Vim for development, even over Textmate on OS X.

A large amount of the Rails developers are using (gasp) Macs, which has actually got me thinking in that direction.

Although I haven't tried it, Ruby in Steel gives you a Ruby IDE inside the Visual Studio world, and IronRuby is the .NET flavor of Ruby, if you're interested.

As far as books are concerned, the Programming Ruby (also known as the Pickaxe) book from the Pragmatic Programmers is the de-facto for learning Ruby. I bit the bullet and purchased that book and Agile Web Development with Rails; both books have been excellent.

Peepcode screencasts and PDF books have also been great for getting started; at $9 per screencast it's hard to go wrong. I actually bought a 5-pack.

Also check out the following:

I've burned through the backlog of Rails and Rails Envy podcasts in the past month and they have provided wonderful insight into lots of topics, even regarding software development in general.

Sprockets tends to be quite verbose in the (dev) log by default under Rails 3.1 (RC1):

Started GET "/assets/application.css" for 127.0.0.1 at 2011-06-10 17:30:45 -0400
Compiled app/assets/stylesheets/application.css.scss  (5ms)  (pid 6303)


Started GET "/assets/application.js" for 127.0.0.1 at 2011-06-10 17:30:45 -0400
Compiled app/assets/stylesheets/default.css.scss  (15ms)  (pid 6303)

...
Started GET "/assets/default/header_bg.gif" for 127.0.0.1 at 2011-06-10 17:30:45 -0400
Served asset /default/header_logo.gif - 304 Not Modified  (7ms)  (pid 6303)
Served asset /default/header_bg.gif - 304 Not Modified  (0ms)  (pid 6246)
Served asset /default/footer_bg.gif - 304 Not Modified  (49ms)  (pid 6236)
...

I'd like to either reduce the level of verbosity or disable it altogether. I'm assuming there is a clean way to disable or reduce the verbosity of the logging by adding a config line in either environment.rb or development.rb similar to config.active_record.logger = nil which silences ActiveRecord SQL statements.

Answered By: choonkeat ( 246)

Place the following code in config/initializers/quiet_assets.rb

if Rails.env.development?
  Rails.application.assets.logger = Logger.new('/dev/null')
  Rails::Rack::Logger.class_eval do
    def call_with_quiet_assets(env)
      previous_level = Rails.logger.level
      Rails.logger.level = Logger::ERROR if env['PATH_INFO'] =~ %r{^/assets/}
      call_without_quiet_assets(env)
    ensure
      Rails.logger.level = previous_level
    end
    alias_method_chain :call, :quiet_assets
  end
end

Updated: now works for Rails 3.2 too (previous attempt fixes before_dispatch now we're going for the root rack call instead)

Update: A proper Rack middleware solution (instead of fragile alias_method_chain) from @macournoyer https://github.com/rails/rails/issues/2639#issuecomment-6591735

199
lucianosousa

How can I remove rvm (ruby version manager) from my system?

Answered By: tadman ( 337)

There's a simple command built-in that will pull it:

rvm implode

This will remove the rvm/ directory and all the rubies built within it. In order to remove the final trace of rvm, you need to remove the rvm gem, too:

gem uninstall rvm

If you've made modifications to your PATH you might want to pull those, too. Check your .bashrc, .profile and .bash_profile files, among other things.

You may also have an /etc/rvmrc file, or one in your home directory ~/.rvmrc that may need to be removed as well.

195
Sokmesa Khiev

When I want to create a Ruby on Rails project, I get the message below.

/usr/lib/ruby/gems/1.8/gems/activesupport-2.3.8/lib/active_support/dependencies.rb:55: uninitialized constant ActiveSupport::Dependencies::Mutex (NameError)
    from /usr/local/lib/site_ruby/1.8/rubygems/custom_require.rb:36:in `gem_original_require'
    from /usr/local/lib/site_ruby/1.8/rubygems/custom_require.rb:36:in `require'
    from /usr/lib/ruby/gems/1.8/gems/activesupport-2.3.8/lib/active_support.rb:57
    from /usr/local/lib/site_ruby/1.8/rubygems/custom_require.rb:36:in `gem_original_require'
    from /usr/local/lib/site_ruby/1.8/rubygems/custom_require.rb:36:in `require'
    from /usr/lib/ruby/gems/1.8/gems/rails-2.3.8/lib/rails_generator.rb:31
    from /usr/local/lib/site_ruby/1.8/rubygems/custom_require.rb:36:in `gem_original_require'
    from /usr/local/lib/site_ruby/1.8/rubygems/custom_require.rb:36:in `require'
    from /usr/lib/ruby/gems/1.8/gems/rails-2.3.8/bin/rails:15
    from /usr/bin/rails:19:in `load'
    from /usr/bin/rails:19

What has gone wrong? How do I to fix it?

Answered By: Aaron ( 180)

In case you can't upgrade to Ruby on Rails 2.3.11 (and to expand on douglasr's answer), thread must be required at the top of boot.rb. For example:

require 'thread'

# Don't change this file!
# Configure your app in config/environment.rb and config/environments/*.rb
...
189
Nate Bird

Since upgrading to Rails 3.1 I'm seeing this warning message in my development log:

WARN Could not determine content-length of response body. Set content-length of the response or set Response#chunked = true

What does this mean and how can I remove it? Is it a problem?

Answered By: Luis Lavena ( 148)

Asked the same question to one of Rails-Core's members:

https://twitter.com/#!/luislavena/status/108998968859566080

And the answer:

https://twitter.com/#!/tenderlove/status/108999110136303617

ya, it's fine. Need to clean it up, but nothing is being hurt.

I've installed devise on my app and applied the following in my application.html.erb file:

<div id="user_nav">
    <% if user_signed_in? %>
        Signed in as <%= current_user.email %>. This cannot be cheese?
        <%= link_to 'Sign out', destroy_user_session_path %>
    <% else %>
        <%= link_to 'Register', new_user_registration_path %> or <%= link_to 'Sign in', new_user_session_path %>
    <% end %>
</div>

I ran rake routes and confirmed that all the routes are valid.

Also, in my routes.rb file I have devise_for :users and root :to => "home#index" so this is driving me insane.

I get the following routing error when clicking the "Sign out" link:

No route matches "/users/sign_out"

I can't figure out what's causing the routing error! Please help!

Thank you for reading.

Answered By: Jessie Dedecker ( 256)

I think the route for signing out is a DELETE method. This means that your sign out link needs to look like this <%= link_to "Sign out", destroy_user_session_path, :method => :delete %>. Yours doesn't include the :method => :delete part. Also, please note that for this to work you must also include <%= javascript_include_tag :defaults %> in your layout file application.html.erb).