Agile Web Development with Rails

Sam Ruby, David Thomas, David Heinemeier Hansson

Mentioned 15

Provides information on creating Web-based applications with Rails 3.2 and Ruby 1.9 and each of the examples has been tested with Ruby 1.8.7, 1.9.2, and 1.9.3.

More on Amazon.com

Mentioned in questions and answers.

When I say { :bla => 1, :bloop => 2 }, what exactly does the : do? I read somewhere about how it's similar to a string, but somehow a symbol.

I'm not super-clear on the concept, could someone enlighten me?

There're some quotes from the famous book Agile Web Development with Rails, which may be helpful to understand the symbol as well :

Rails uses symbols to identify things. In particular, it uses them as keys when naming method parameters and looking things up in hashes.

redirect_to :action => "edit", :id => params[:id]

You can think of symbols as string literals that are magically made into constants. Alternatively, you can consider the colon to mean "the thing named", so :id is "the thing named id".

Most of the time, whenever I hit a website that looks "bubbly" in nature, and all prettified in those pastel-like colors, I think to myself, "This was probably done with Rails." And, lo and behold, after some digging into the site's information pages I discover this is actually true. So, I pose the question, not knowing much about Rails but enough about Django to understand how the database stuff works:

Does RoR have any display-specific qualities that affect how a web page looks? Or do all RoR devs naturally use the same Adobe tools to make everything look so ubiquitous?

Rails does add some stuff to the front end. Like to every html form, it will add a hidden input element authenticity_token.

You can also tell because rails URLs and form actions will never end with suffixes like .aspx or .php or .html or .jsp, and they won't usually append ?query=book&encoding=utf8 like you see on google. And they won't usually have superlong crufties like you see on amazon (eg http://www.amazon.com/Agile-Web-Development-Rails-Ruby/dp/1934356549/ref=sr_1_1?ie=UTF8&qid=1297922135&sr=8-1). Instead Rails prefers simple routing URLs. If amazon were written in rails, you might instead expect amazon.com/books/Agile-Web-Development-Rails-Ruby

So there are ways to spot a Rails app. I expect other web frameworks, especially the ones that emulate rails, would duplicate some or all of these features, so this isn't a sure-fire method, but it helps.

I am currently developing some plugins for Redmine, and I must say, I'm a bit disappointed with the lack of documentation available on this subject.

Normally, If I am looking for explanations on classes/methods, I need to spend a consistent amount of time browsing trough the core classes, and striving to understand the code written there (It seems that some people forgot to document their code, unfortunately).

I've checked their forums http://www.redmine.org/projects/redmine/boards, and it seems to take forever in order for a question to be answered.

That's why I would like some advice regarding some good API documentation/books/forums on this subject.

I know this maybe too-late for the original question poster but might help someone else in a similar situation. Below links are for a total newbie (like me) to RubyOnRails but someone who's programmed before. You can pick and choose the relevant ones as per your skill level.

Understanding Redmine (functionality):
If you're not familiar with Redmine or administering other Issue Tracking Software Mastering Redmine book is an ok place to start. It's not very densely packed so it'll help only as a structured organization of information. If you want more dense information go through the documentation instead.

Understanding Redmine Plugins:
"Redmine Plugin Extension and Development" by Alex Bevilacqua has just been released (March 2014). It's available both in print and ebook formats from packtpub.

I'm going through the book myself as I need to customize/rewrite a plugin for Redmine. I'm new to Rails/Ruby/Redmine myself. Though I'm from Unix/C++ background still getting to know the ropes of Ruby, Rails, Redmine via following books.

Understanding Rails:
I found the book Agile Web Development with Rails to be a good enough intro to Rails for programmers from other languages.
Note: Target audience seems to be Rails developers but it should be possible to get through that learning curve by browsing github redmine plugin repositories.

Understanding Ruby:
Programming Ruby (the PickAxe Book)

Understanding Ruby Metaprogramming idioms (used in Rails):
On the surface Ruby looks like most scripting languages it is the use of MetaProgramming and Dynamic nature of Ruby Object Model that allows making complex internal gymnastics invisible to newbies.

A single line of Rails code contains enough such tricks to fill a small book.
Fortunately such a book has already been written - Ruby MetaProgramming book in Pragmatic Programmers series. It's superb to come to grips with this Mixin based Dynamic MetaProgramming. Rails and Redmine use plenty of these tricks as hooks etc to get the work done.

Excellent Video on Ruby Object Model by Dave Thomas
Video on Ruby Object Model and Meta Programming

I'm a Django person going into Rails, and I want a guide that shows me all the popular "conventions".

For example: plurality, _form.html.erb, stuff like that.

Can someone list them here? Or a webpage?

If you want the official conventions, then nothing beats the original Rails book: Agile Web Development with Rails

But if you want the unwritten conventions, here's a good start: acts_as_good_style

Rails:
Rails Style Guide : https://github.com/bbatsov/rails-style-guide
Ruby Style Guide : https://github.com/bbatsov/ruby-style-guide
Rails Best Practises : http://rails-bestpractices.com

There used to be a "Complete Guide to Rails Plugins (2 part article) :" but site is gone now http://nubyonrails.com/articles/the-complete-guide-to-rails-plugins-part-i

Ruby:
Ruby From Other Languages : https://www.ruby-lang.org/en/documentation/ruby-from-other-languages
Ruby Language Tips, Tricks, Dos and Don'ts and Gotchas : http://www.zenspider.com/Languages/Ruby/QuickRef.html

Another way to understand mysterious workings of a framework is to understand the principles and implementation details on which it is built. Internals often dictate why something must be just-so. "Rebuilding Rails" is a book which claims to give this X-Ray vision into Rails internals. It's available for a price though. Might be cheaper to just browse the source-code with source-insight or some Rails IDE instead.

The book 'The Rails Way' is a good insight into different aspects of WHY Rails is the way it is.

Chapter 18 onwards of the book "Agile Web Development with Rails" talks about Rails module-by-module i.e. "what each module does, how to extend or even replace the module and why you'd even want to do so".

Many of the "magic"/conventions arise by using Ruby Meta-programming features you might find Pragmatic Programmers book Meta-programming Ruby - Program like the Ruby Pros useful.

Though not accessible for a novice programmer more intermediate/advanced programmers can browse the Rails source code at Github Rails Repository

I've been developing a new rails project for a few weeks, and while I am amazed at the awesome plugins and some of the really great features in the frameworks... I am a little disappointed too. And I am worried.

I think I made a mistake.

Should I press on, or go back to what I was familiar with? (Java/Spring)

  1. It seems that unless you are looking for "simple examples", googling for the exceptions to the rule, special cases and so on really hampers productivity and is increasingly becoming the norm for me.

  2. Documentation and examples from the main site, blogs, screencasts, etc. are mostly out of date. For every 5-10 examples that are out there, 1 of them is actually correct.

  3. Doing anything new that should "just work" almost never does. I try and following documentation and examples, but my results seem to vary and I discover problems never mentioned in the documentation and examples. This seems to happen all the time actually.

  4. My experience with trying out CoffeeScript and it's integration with Rails was a disaster. Not being able to see what the problem is whenever a "compiler error" occurs is beyond frustrating.

  5. ActiveRelation is really awesome, until you need to make a query that joins 7 tables. Then it starts to break down. I think it's possible that you can get that 7-table join query done in Hibernate quicker and finished reliably the first time you are learning it.

  6. Testing is actually really hard in Rails. There's just too much "Magic" going on. Since Ruby is dynamic, I have no idea what I need to call to test something appropriately. There always seems to be exceptions to the rule.

    For example, Devise works like you would expect... until you want to test Devise in helpers. It just won't work, so you have to invent the Devise-generated methods in your tests to make the tests pass. You don't need to do this for controllers.

    There are some blogs that teach how to test using Rails, but they are extremely trivial and not very helpful. Some of them are just bad actually. I found how to effective test validations in a far superior manner than many of the blogs I found for example. I just find that I am often on my own when it comes to testing.

  7. Why does images and stylesheets not work properly when you switch to production for? This is insane. Tons of people ask this if you google it... yet the framework doesn't "just work".

    I am scared to death to deploy this application eventually. The production version doesn't seem to work anything like the development version would. Scary.

  8. For some reason, after adding jquery-rails and devise, the authentication token wasn't getting passed during ajax requests. I had to add the 4 lines of javascript code to make it work. This took me 5 hours. In Java, because you have proper sessions, you never even need to think about this type of stuff.

  9. Tests run really slow. I have about 780 tests, and it already takes much longer than a Java project which has 1800 tests.

  10. Testing the application in the browser is really slow. It takes like 1/4 of a second to render some of the pages... and there isn't even that much ORM action going on! Even for pages with 1 database query, it takes 100-200 milliseconds. This is crazy.

  11. Documentation is often out of date. For example, trying to override things in Devise was a pain because the documentation actually told me to do the wrong thing. Only after hours of googling and waiting 48 hours on another forum was I able to have someone tell me what I needed to do. All I wanted to do was have the login form reject a user where User.enabled was false. That's it. It turns out, I was overriding "active?" instead of "active_for_authentication?" - which was an error in the RDoc's.

  12. The ORM behaves in really strange ways that are not intuitive at all. Inserts/updates work differently when you are associating new objects. It also doesn't cascade like Hibernate would... which makes me suspect that it's not tracking dirty objects? If it is... then why isn't cascading set by default? Things like this are hardly good defaults. Isn't Rails supposed to be great at good defaults?

After 2 weeks, the number of "gotchas" hasn't really slowed down. I am really worried and scared. I know Java isn't immune to gotchas and problems, but I generally ran into problems about 2-3 times a month - not 30 in one week.

I am almost thinking the lack of agility when using Java/Spring is not much of a burden now when you consider how stable, fast and predictable the platform is. You maybe write a bit more code, but you know exactly what's going on... you never really deal with silent failures... and things do tend to work a lot more reliably.

I am starting to question using Rails for this new project.

Best thing you can do is get hold of the 'Agile Web Development with Rails', when I started out a few years back, reading and working over the examples in this book really helped me understand how things should work, it also acts as a great reference that you can dive into whenever you want to read up on certain topics.

The latest version seems to be: http://www.amazon.co.uk/Agile-Development-Rails-Pragmatic-Programmers/dp/1934356549/ref=sr_1_1?ie=UTF8&qid=1305991885&sr=8-1

I’m going to make an advertising system from scratch and put it inside of my Ruby on Rails Web Application. What books do you recommend and subjects (Algorithms, SQL?) should I learn in order to make this happen, where does one start?

I want the system to take User Data and when businesses advertise, the Users will get recommended Ads based on their likes, dislikes and other data. The advertising will take place only in my web application and on my website. I believe I am looking to do something similar to Facebook Ad System (images) and Google Ad Words, how did they do it?

Thank you.

P.S. I have little experience in Rails, Ruby language,Computer Science and programming in general but i am learning fast and building my application easily.

Ilya Grigorik did an awesome writeup with lots of code samples on this subject. See http://www.igvita.com/2007/01/15/svd-recommendation-system-in-ruby/

If you mean books on Ruby and Rails, I can recommend:

Programming Ruby (AKA "The Pickaxe")

Agile Web Development with Rails

Those were the starting points of my Ruby career.

I'm currently writing my bachelor thesis about recommender systems with location based social networks. For the basics of recommender systems have a look at these books which helped me a lot: http://www.amazon.de/Recommender-Systems-Introduction-Dietmar-Jannach/dp/0521493366/ref=sr_1_1?ie=UTF8&qid=1300796937&sr=8-1

http://www.amazon.de/Recommender-Systems-Handbook-Paul-Kantor/dp/0387858199/ref=sr_1_3?ie=UTF8&qid=1300796937&sr=8-3

and if you speak german, this book gives a good survey: http://www.amazon.de/Empfehlungssysteme-Grundlagen-Konzepte-Andr%C3%A9-Klahold/dp/3834805688/ref=sr_1_2?ie=UTF8&qid=1300796937&sr=8-2

I'm new to ruby and rails and walking (crawling?) through the tutorial. the second project uses scaffolding to create a user that consists of a name and email address. when i try to view the users screen I get the following:

ExecJS::RuntimeError in Users#index

Showing /home/max/rails_proj/demo_app/app/views/layouts/application.html.erb where line #6 raised:

湉異⁴牅潲㩲唠歮潮湷漠瑰潩⼢浴⽰硥捥獪〲ㄱ㤰㔲㐭㜲ⴲ㠱㝮穩ⴰ⸰獪•灳捥晩敩⹤਍
  (in /home/max/rails_proj/demo_app/app/assets/javascripts/users.js.coffee)
Extracted source (around line #6):

3: <head>
4:   <title>DemoApp</title>
5:   <%= stylesheet_link_tag    "application" %>
6:   <%= javascript_include_tag "application" %>
7:   <%= csrf_meta_tags %>
8: </head>
9: <body>
Rails.root: /home/max/rails_proj/demo_app

Application Trace | Framework Trace | Full Trace
app/views/layouts/application.html.erb:6:in `_app_views_layouts_application_html_erb__1031573605_1065816420'
app/controllers/users_controller.rb:7:in `index'

I am using windows xp, cygwin, rails 3.1.0 (i've tried the new rc1 also), ruby 1.8.7.

I found this error on google and there's supposedly a fix which i've tried to use (the execjs gem 1.2.9) but that doesn't seem to fix it for me.... i have tried all the fixes (to the best of my limited ruby etc ability at this point) but nothing seems to work although the error message is sometimes different - still errors on the same line.

I've tried to uninstall and reinstall cygwin, ruby, rails etc.. to no avail so far...

any feedback would be great!

As someone who tried to do that book on windows, I have 2 pieces of advice:

  1. Install Ubuntu to run ruby on rails. It is a little bit of work, but if you are going to invest time and effort it is worth it 100 times over. You can set up dual install with existing windows. Or, just find an old computer and install it on there. It uses much less power than windows xp and only about 300 Mb of memory.

  2. Start with Agile Web Development with Rails. http://www.amazon.com/Agile-Development-Rails-Pragmatic-Programmers/dp/1934356549 . It is a much better first tutorial.

hi im new to ruby on rails application development im just wondering what basic gems i need for my ruby on rails im a beginner and don't know what gems are important for a beginner like me

thanks please help

I highly recommend pry -- it's unbeatable for exploring your code and data. In Rails it's a pleasure to use as a rails console replacement.

I also recommend a gem of a book (see what I did there?) called Rails AntiPatterns which will help you start writing clean Rails code. And The Rails Way, if you haven't already.

There are so many gems, that it's best to start looking only when you have an itch you assume someone else must have already scractched.

Generally I'd suggest picking up a good book and working through it.

If Rails is what you're interested in, then check out;

They will introduce you to the design patterns and workings required to build apps in Ruby and Rails.

And consequently, along the way, you'll find out how and when to use various different gems.

Asking what gems to use, without a context doesn't really get you anywhere, unfortunately.

I implemented the official Creating the Blog Application project as per the directions given. But I am not getting the idea of link_to used in this project like:

<td><%= link_to 'Show', post %></td>
<td><%= link_to 'Edit', edit_post_path(post) %></td>
<td><%= link_to 'Destroy', post, :confirm => 'Are you sure?', :method => :delete %></td>

given in app/views/posts/index.html.erb file, also corresponding code in app/controllers/posts_controller.rb for rendering html pages in app/views/posts/ directory.

If I want to render a new html page say index2.html.erb in app/views/posts/ directory that does not have 'Edit' and 'Destroy' links compared to index.html.erb, then how should I write link_to and corresponding code in posts_controller.rb ?

If you want an action called index2, say for a example URL like http://localhost:3000/posts/index2, then you need to:

  1. Create an action (method) for it in the posts_controller.rb:

    class PostsController < ApplicationController
      ...
      def index2
      end
      ...
    end
    
  2. Create a view file for it in the app/views directory called index2.html.erb

  3. Add a route to config/routes.rb, for example:

    resources :posts do
      member do
        get 'index2'
      end
    end
    

To link to the newly created index2 page, add a link in some other html.erb file to it like this:

link_to "index 2",index2_post_path

I highly recommend the book Agile Web Development with Rails (Pragmatic Programmers)

I'm following through the tutorial from the book Agile Web Development with Rails and I found the following code:

def User.encrypt_password(password, salt) 
  Digest::SHA2.hexdigest(password + "wibble" + salt)
end

Looking into the Digest source code (digest.rb and digest/sha2.rb inside the lib directory in my ruby installation), however, I can't seem to find where the hexdigest method is defined, but yet the code seems to work just fine.

Can someone enlighten me how this happens? I assume that I need to look for a code that somehow looks like:

def hexdigest(...)
   ...
end

The hexdigest part, and several other similar methods are written as a C extension for speed. It's found in ext/digest/ in the Ruby source.

static VALUE rb_digest_instance_hexdigest(int argc, VALUE *argv, VALUE self) is defined on line 216 in ext/digest/digest.c in my Ruby 1.9.2-p0 source. It just calls a bunch of other functions, but it might be a starting point at least.

For SHA2, there is another ext/digest/sha2/sha2.c that contains those functions. digest.c is just the basics, "extended" by the other ones

I already started learning online but everything out there seems oriented to developers not designers with no baggage.

I'm a graphic designer and I'm coding recently and I am very decided to master RoR.

Thanks for the nudge!

If you're the visual type you might enjoy Why's Poignant Guide as an introduction to Ruby. Then perhaps Agile Web Development with Rails. A working knowledge of HTML, CSS, and Javascript are also a must.

I am following the book Agile Development with Rails(http://www.amazon.com/Agile-Development-Rails-Pragmatic-Programmers/dp/1934356549). In Chapter 9, it defines a private method in application controller:

class ApplicationController < ActionController::Base
    protect_from_forgery

    private

    def current_cart 
      Cart.find(session[:cart_id])
    rescue ActiveRecord::RecordNotFound
      cart = Cart.create
      session[:cart_id] = cart.id
     cart
   end
end

It says "This makes this method only available to other controllers, and in particular it prevents Rails from ever making it available as an action on the controller." I am wondering why this will make a private method available to other controllers? Iknow private methods can only be accessible inside the same class. Is there any magic behind this?

Private methods in ruby don't work the same way as they do in other languages. In ruby we can call a private method from within the class it is declared in as well as all subclasses of that class. This explains why you can declare a private method in ApplicationController and have it available in all other controllers, as all of your other controllers are inherited from ApplicationController.

For more information I suggest researching ruby access control. To start, there is a great article here.

Hope this helps!

I leaned ruby, but the syntax and the file structure in rails is very difficult for me to understand, there are many things that I need to follow their "rules" to do, for example, I need to generate the db using the migration... It is not suggested to do with typically typing SQL cmd, it makes me very difficult to move on... Any suggestion on how to learn the whole file and how the structure works? Thank you.

For a newbie, best way to learn Rails is to follow a book fro start to the end, and implement each of the examples in the book. I would recommend you following books:

Ruby on Rails 3 Tutorial-Learn Rails by Example

Agile Web Development with Rails

I find these two books excellent resources. Make sure you follow these books really well, one book at a time.

Following a book is much better practice than learning in bits-and-pieces from web.

I'm working through Agile Web Development with Rails

In part E3, it says to replace the following method:

def destroy
  @cart = Cart.find(params[:id])
  @cart.destroy

with

def destroy
  @cart = current_cart
  @cart.destroy  

where

def current_cart
  Cart.find(session[:cart_id])
rescue ActiveRecord::RecordNotFound
  cart = Cart.create
  session[:cart_id] = cart.id
  cart
end

My question is, what is the advantage of using the second method over the first? I can't see any circumstance where the second would fail? This is calling the method from:

<%= button_to 'Delete Cart', method: :destroy %>

From within the cart view. Doesn't it implicitly always pass in the correct cart_id?? Or is this modification for destroy for future uses, for example when we are trying to delete the cart from another view? If this latter explanation is correct, do we need to always store id's in the :session hash?

Thanks for your help.

For starters, it offers a some protection against someone maliciously modifying the url and passing &cart_id=ID_TO_CART_I_DONT_OWN. See https://www.owasp.org/index.php/Top_10_2010-A4.

You're also saving yourself a database lookup by getting the cart from the session [although rails is pretty good with db caching by default]. About it possibly failing, what happens if the record no longer exists by the time you hit the "Delete Cart" button ? Cart.find(params[:id]) will raise an exception that you're not handling, the second method will handle the exception and fail quietly; this is not necessarily always a good thing.

I am looking for a good Ruby teaching guide (in pretty much any form) that gives a good sense of what is needed for programming with the Rails framework.

I took up Rails with the Agile Web Development with Rails 2nd Edition. I have their latest (4th) edition and recommend it, but there are lots of other resources out there now.

One in particular that I would very much recommend is the free Ruby on Rails Tutorial by Michael Hartl. It's up to date and teaches you how to use not only Ruby and Rails, but also other modern and important tools such as RVM for Ruby/gem management, Git for version control and RSpec for testing. It encourages a great test-driven workflow, so I'd recommend it even if you're not a beginner. I actually used this tutorial a few months back to refresh my memory and get into the new Rails 3 after having been out of it for over a year.

After you're comfortable with the Rails framework, then you should learn the Ruby language it is built upon. This is the stage I am at. Some of the books I'd recommend for learning Ruby are:

  • Eloquent Ruby - teaches you the Ruby way in many chapters covering a wide spectrum of the Ruby language. Great read for polishing and enforcing your Ruby knowledge, and also great to re-read just to reinforce everything!
  • The Ruby Programming Language - co-authored by the author of Ruby himself, Yukihiro Matsumoto...need I say more? This is quite in-depth so not great for beginning to learn the language but great for helping you to master it.
  • The Well Grounded Rubyist - currently going through this book. It is well written and covers a lot of ground, good for getting the hang of Ruby, but probably assumes you're not a programming newbie.

Obviously this is based on my experience and recommendations I have received from friends and colleagues, so I'm not saying this is the path for everyone interested in Ruby/Rails, but so far it's working for me. I'll be interested in seeing what resources others recommend here.