RailsCasts Pro episodes are now free!

Learn more or hide this

Recent Comments

Avatar

The issue was due to:

Running: rake assets:precompile
rake aborted!
could not connect to server: Connection refused
Is the server running on host "127.0.0.1" and accepting
TCP/IP connections on port 5432?

To fix the issue put this in your application.rb

config.assets.initialize_on_precompile = false

then run again...

Avatar

I'm the only one getting issue with using custom mixin methods on heroku??

ActionView::Template::Error (.border-radius is undefined

I had imported these files

@import "twitter/bootstrap/variables";
@import "twitter/bootstrap/mixins";
@import "twitter/bootstrap/navs";

Avatar

While Derby and Meteor are nice at the first glance both a still in their –promising– infancy.

I expect to kind of web app to dominate in the future: Highly interactive and responsive apps build using frameworks like Derby, Meteor, Slipstream or alike. And static HTML assets / pages where no interactivity is necessary.

Rails will not be able to compete with any of these hyper modern Node frameworks as long as the Rails project avoids integrating Websockets as a core feature. We could of course integrate Juggernaut, Faye or Torquebox Stomp but would be left on our own devices. But then every one of us must build a synchronization mechanism.

I'm just considering AngularJS and Joosy. And whether generators would be useful to write all the boilerplate code by introspecting the existing models.

Avatar

I used this and it works also:

ruby
def sort
    params[:faq].each_with_index do |id, index|
        faq = Faq.find(id)
        faq.update_attribute(:position, index) if faq
    end
    render nothing: true
end

In this case, it uses update_attribute instead of update_all...update_all was giving me an error with Mongoid 2

Avatar

SSL offload is a common practice to reduce load on non-edge servers

Avatar

for non-heroku users: If you want to get an access all-site through HTTPS-only what is the reason to handle SSL detection through Rack and ActionDispatch? All that code can be simplified by using redirection through web-server 301 permanent redirect.

nginx (http block)
server {
    listen       80;
    server_name  host.com *.host.com;
    rewrite ^(.*) https://$host$1 permanent;

    access_log /dev/null;
    error_log /dev/null;
}

A specific header Strict-Transport-Security tells the browser that all future requests (and cookies as well) should go through SSL only. Don't use SSL for partly access, because cookies can be hacked while you are non-SSL page.

Don't forget about scaling patterns such as SSL offload, so every application servers should not used an SSL, but edge load balancers only. So permanent redirection on web-server side only (not application) can help with scaling without any modifications of Rails codebase.

Avatar

ssl_protocols SSLv2 SSLv3 TLSv1;

Ryan, are you sure about SSLv2? It's pretty unsecured protocol.
I spent a time on Nginx security and would like to share my config

nginx (http block)
    ssl_protocols             SSLv3 TLSv1 TLSv1.1 TLSv1.2;
    ssl_ciphers               RC4:HIGH:!aNULL:!MD5;
    add_header                Strict-Transport-Security "max-age=16070400; includeSubdomains";
    add_header                X-Frame-Options DENY;

To enable TLS 1.1/1.2 protocols you need to compile Nginx with openssl > 1.0.x.
Some useful headers can help with interaction through HTTPS only (from all feature requests) and prevent an option to load your site into iframe.

bash
  $ wget http://www.openssl.org/source/openssl-1.0.1c.tar.gz
  $ tar xzvf openssl-1.0.1c.tar.gz && rm -f openssl-1.0.1c.tar.gz
  $ configure --with-openssl-opt=no-krb5 --with-openssl=/usr/src/openssl-1.0.1c

No-krb5 to disable Kerberos 5 authentication protocol which causes Nginx segfaults by Internet Explorer request (rarely bug)

Qualys SSL test can help in the search for vulnerabilities in web-server configuration.

Avatar

I recently created a gem to aid in building and rendering a monthly calendar. The API is much less magical than the table_builder gem, with all the same features. Check it out at https://github.com/austinthecoder/cal. I hope it helps.

Avatar

Very nice episode! But why does rubber upload code to all instance? I would expect it to upload the files only for the instance with the app role.

Avatar

Restarting nginx: nginx: [emerg] unknown directive "server" in /etc/nginx/nginx.conf:10
nginx: configuration file /etc/nginx/nginx.conf test failed

About this error, i found it because of my fault.. i should insert the SSL configuration inside nginx.conf in my rails config folder.

And i still have this error:

Error 102 (net::ERR_CONNECTION_REFUSED): The server refused the connection.

Avatar

I'm having the same issue did you find a solution?

Avatar

I did all the instructions and successfully deployed, but then when i tried to access it, it was automatically redirect my browser to https://IP.

This is what Chrome said:

Error 102 (net::ERR_CONNECTION_REFUSED): The server refused the connection.

I though it was because i forced the SSL in production.rb and then i set it to false and redeployed. But nothing changed!

After that i set the ssl force back and try to install SSL using the instruction in http://railscasts.com/episodes/357-adding-ssl, and i had a problem in nginx when i tried to install:

Restarting nginx: nginx: [emerg] unknown directive "server" in /etc/nginx/nginx.conf:10
nginx: configuration file /etc/nginx/nginx.conf test failed

Can anyone give me a solution for this? Thanks in advance :)

Avatar

If every API users has a API_KEY or Token, you can have a column like 'requests_count' and increment it with each request. When you reach lets say 500, you can return a 500 or something and have rake tasks reset the count after 24 hours or so.

Avatar

Ursusurus,

Watch the REVISED version at http://railscasts.com/episodes/250-authentication-from-scratch-revised which was produced on 2/25/12. This version was produced 1/24/11 and is out of date.

Chip

Avatar

I was getting the error:
>$ rake db:migrate
'rake aborted!
FATAL: role "blog" does not exist'

so I had to create a superuser 'blog':
>$createuser -s blog

Avatar

I got an error on jquery:
$("form").on is not a function

I upgrated jquery to 1.7.1, but it still error.
Thanks to anyone who can help.

Avatar

Joshua Sierles is from 37signals.
His cookbook at https://github.com/jsierles/chef_cookbooks
is better maintained than the 37signals cookbook

The 37signals cookbook was last updated 2 years ago, by jsierles
jsierles cookbooks was updated 14 days ago

Avatar

I'm a little bit confused. Previously you made all Omniauth authentication options exist via the authentication model. Here you seem to have broken from that by making the user the authentication provider holder. Why isn't identity just another authentication?

The challenge I see is that I want to manage roles for a user, but with the user constructed the way that it is, it would appear I have to create another variation of a user model in order to do make a user a truly singular entity (with many users instead of authentications? both users and authentications?)

Avatar

Thank you Ryan, Nice!!, I was trying with Facebook that worked well, however when I tried the logout to login again with other Facebook account that didn't worked, is there a way to really logout from Facebook?

Thank you

Avatar

Seems EventMachine is broken as of right now, so the gem install fails.

Avatar

Hi, the application is running well with firefox but not with google chrome. chrome does not recognize when I click on a field.

Avatar

Thanks guys for the discussion. I also found this good conversion on SO.

My take away is (at least for me), all or nothing seems the best way to go.

Avatar

Right, but most client-facing tools, like Mailchimp, should offer http as well.

Avatar

Thanks again to Ryan.

I've put up a quick post on how to use this approach for warden.

http://fullware.net/prevent-rails-session-hijack-in-warden/

-Doug
www.fullware.net

Avatar

Using Rails 3.2.3, I did have this error but it is fixed (see below for changes):

You can see I was using different variable names than the example, but hopefully the comparison between the two code snippets below will indicate what might be worth changing in your code.

ERROR
undefined method `klass' for nil:NilClass

BEFORE CHANGES

ruby
<%= user_form.fields_for :aois do |aoi_form| %>
  <%= render 'aoi_fields', f: aoi_form %>
  <%= link_to_add_aois "New AOI", aoi_form, :aoi %>
<% end %>

AFTER 2 CHANGES (no more errors)

ruby
<%= user_form.fields_for :aois do |aoi_form| %>
  <%= render 'aoi_fields', f: aoi_form %>
<% end %>
<%= link_to_add_aois "New AOI", user_form, :aois %>

I hope that is helpful to some folks.

Thanks for these truly awesome tutorials.

Avatar

I tweaked my setup a bit to do this, but also to set up an easy mapping to port 3000 for when I'm switching between apps. Add the host 3000.local to your /etc/hosts and then for nginx:

-Doug
www.fullware.net

    upstream local_3000 {
      server 127.0.0.1:3000;
    }
    
    server {
      server_name  3000.local;
      listen       80;
      listen       443 default ssl;
      send_timeout 3600; # For debugging with breakpoints

      #ssl                  on;
      ssl_certificate      server.crt;
      ssl_certificate_key  server.key;

      ssl_session_timeout  5m;

      ssl_protocols  SSLv2 SSLv3 TLSv1;
      ssl_ciphers  ALL:!ADH:!EXPORT56:RC4+RSA:+HIGH:+MEDIUM:+LOW:+SSLv2:+EXP;
      ssl_prefer_server_ciphers   on;

      access_log  /usr/local/var/log/nginx/3000_access.log;
      error_log   /usr/local/var/log/nginx/3000_error.log;

      location / {
        proxy_set_header Host $host;
        proxy_set_header X-Forwarded-For $proxy_add_x_forwarded_for;
        proxy_set_header X-Forwarded-Proto $scheme;
        proxy_redirect off;
        proxy_pass http://local_3000;
      }
      
    }
Avatar

That's because the protection feature called MassAssignmentSecurity is active. For a quick and dirty (very dirty) fix just comment the following line in Application.rb
config.active_record.whitelist_attributes = true
This will disable this protection for ALL your models.
You can read something more about it here: Rails Tip #7: Mass Assignment Security

Avatar

This github issue might help you fix the problem, it looks like you want to substitute all references to activerecord with activemodel. Make sure you do it in your locale file too.

Avatar

Hey Thanks Robert. Works like a charm from within the Rails Console. I could not make it work in the plain irb outside of Rails. May be I am missing something?

Avatar

Oh and if you want it to work without rails:

ruby
class Object

  include Rails::ConsoleMethods if defined?(Rails)

  def vim(method_name)
    file, line = method(method_name).source_location
    fork do
      exec("vim +#{line} '#{file}'")
    end
    Process.wait
    reload! if defined?(Rails)
  end

  alias :v :vim
end
Avatar

Try the following:

ruby
if defined?(Rails)
  class Object

    include Rails::ConsoleMethods

    def vim(method_name)
      file, line = method(method_name).source_location
      fork do
        exec("vim +#{line} '#{file}'")
      end
      Process.wait
      reload!
    end

    alias :v :vim
  end
end

Remove the reload bits if you don't require them.

Avatar

Are the attributes translateable? The default path (de.activerecord.attributes.message.subject: Betreff) fails.

Avatar

I prefer using an ide debugger, like the one in RubyMine. You can conveniently step through code and inspect variables. Super useful...

Avatar

Tom, Do you have any reference that you can point to for the ELB SSL setup?

Thanks

Avatar

Device, and probably most other Rails authentication solutions, uses Rails built in sessions. To make the Rails session cookie secure in production add the following to the 'Application.config.session_store' setting in 'session_store.rb':

secure: Rails.env == 'production'

Also, if you are using Rememberable, you should have the following setting in 'devise.rb':

config.rememberable_options = {:secure => Rails.env == 'production'}

Avatar

Here's what I got

ruby
Restarting nginx: nginx: [emerg] "upstream" directive is not allowed here in /etc/nginx/sites-enabled/<appname>:1

So I had to keep these lines outside the server block to make it work:

ruby
include /etc/nginx/conf.d/*.conf;
include /etc/nginx/sites-enabled/*;

All of my apps had:

ruby
listen 80;

except for my main app, it had:

ruby
listen 80 default deferred;

So the only difference is I don't have a default app (IP address gets 404 Not Found)

Thanks for your post, that DRYs it up a bit.

Avatar

Note that even with 'config.force_ssl = true' the cookie will be sent in the clear in the first request if someone chooses to access to site without https, so to be secure you should always use secure cookies. It's also a good idea to set the session cookie to HttpOnly to avoid cross site scripting.

Avatar

In one of my queries I used {:id => nil} for 'id IS NULL'. How to write a similar query for 'id IS NOT NULL' ?

Avatar

I'm getting the same error as David Fisher no matter what browser I use. I'm using rails 3.2.5. I've tried both the 'chosen-rails' gem and installing the files by hand.

Object # has no method 'chosen'

Avatar

It really depends on what your placing in the cookie before you decide to secure it. The simple solution would be to encrypt the cookie via bcryt. But its never a good idea to place sensitive data on the client side. Your cookie should really track the user session to query your database securely.

Avatar

Trying to adapt the open a specific method's source at a given line number which Ryan demonstrates using TextMate to VIM. Here is my code in the .irbrc file:

ruby
class Object                                                                                  
    def v(method_name)
      file, line = method(method_name).source_location
      `vi '#{file}' +#{line}`
    end
 end

Here is what I get when try to follow the number_to_currency example:

helper.v(:number_to_currency)
Vim: Warning: Output is not to a terminal

Any ideas anyone?

Thanks in advance.

Bharat

Avatar

...but would I use the access_token field to identify the user calling the API?

Avatar

Very useful, thanks, Ryan!!!

Real life example of similar auth you can find at http://gistflow.com (open source).

Famous Egor Homyakov hacked us using bug described here:

http://gistflow.com/posts/174

The thing is that if you store auth_token in cookies csrf protection will not work.

Good luck everyone with safe auth :)

Avatar

I posted a question on Stack Overflow that is related to this episode. I'd be much obliged if anyone could provide some insight.

rails infinite scroll ajax actions on page > 1 items

Avatar

I just went through and followed this for a Rails 3.1.1 app. It was a great help with the appropriate pointers. What I found with my 3.1.1 usage was:

1) I had to adjust the config/environment.rb line(s).
Myappname::Application.configure do
config.time_zone = "Eastern Time (US & Canada)"
end

2) I am using simple form and found that just <%= f.input :time_zone %> does the automagic for me, which was a treat

Thanks for the great content! The 'classic' episodes remain a useful reference.

Avatar

A ton of useful information as usual :)
I use the ruby-debug gem and now debugger gem, which you recently covered in a revised episode. For a lone developer working by himself, being able to use the ruby-debug/debugger gem is an essential survival skill.
I was wondering if you use any techniques that are specifically applicable to debugging and finding what is not working faster? I haven't kept up with the Pry gem and tried to use it following your episode on it, but it was not a replacement for ruby-debug. Anything which helps find those pesky bugs faster would be super useful.

Avatar

The Textmate snippet for Sublime Text -

ruby
class Object
  def subl(method_name)
    file, line = method(method_name).source_location
    `subl '#{file}:#{line}'`
  end
end