RailsCasts Pro episodes are now free!

Learn more or hide this

Recent Comments

Avatar

Hi Ryan, really nice episode. Have you ever tried to provide omniauth for two models in the same application (e.g. Manager and Employee) for the same provider?

The problem lies in the routes used by omniauth. There's a single entry point for both the authentication route and the callback (per provider), so there's no way to differentiate between the two models.

One potential solution, could be to provide a parameter during authentication (e.g. :type => "manager") and handle it during the callback.

Do you know of any other solution?

Avatar

Great tut!

But does anyone of you have any problem with openssl savon and the guide above?

I get

OpenSSL::SSL::SSLError (SSL_connect returned=1 errno=0 state=SSLv2/v3 read server hello A: sslv3 alert unexpected message):

Any tips? Do a need to generate a certificate on the server (guide does not state that).

Avatar

If you are going to use pow at all you should be using the powder gem, it will make your life 1000% easier.

Avatar

If you are having trouble getting some of your style changes to apply make sure you remembered generate the scaffold without stylesheets in the previous episode.

Avatar

Hey, thanks for the video. How would this work if the set of items is based on a has_many through model?

for example,

I have a list of pieces like this: @queue.pieces

pieces and queues are related via a has_many through piece_queues

would that work?

Avatar

If this is how you handle deletion application wide, then I don't see a problem with it. All resources already have a destroy action.

Avatar

I can't quite wrap my head around this, but while following this tutorial line-by-line, my Backbone app refuses to render the view template. Please point me in the right direction, as this is my first experience with Backbone, and I've been circling around this problem for the past two days.

This is my /entries.js file:

javascript
class Raffler.Routers.Entries extends Backbone.Router
        routes:
                '': 'index'
                'entries/:id': 'show'
                
        index: ->
                view = new Raffler.Views.EntriesIndex()
                $('#container').html(view.render().el)
                
                
        show: (id) ->
                alert "entry #{id}"

If I were to replace $('#container').html(view.render().el) with $('#container').html('<h1>Raffler</h1>') , it would produce the desired outcome. I don't think the el attribute has a value.

My /index.jst.coffee file:

javascript
class Raffler.Views.EntriesIndex extends Backbone.View

  template: JST['entries/index']
        
        render: ->
                $(@el).html(@template())
                this

Any help is appreciated!!

Avatar

For some of the strangest reason i cannot seem to solve this to save myself .

[106.187.36.187] executing command
** [out :: 106.187.36.187] rake aborted!
** [out :: 106.187.36.187] Invalid CSS after "...f.eot);src:url(": expected > expression (e.g. fr, 2n+1), was "/assets/"/asset..."
** out :: 106.187.36.187

Which leads to :
> failed: "sh -c 'cd /home/deployer/apps/app_name/releases/20120624151117 && bundle exec rake RAILS_ENV=production RAILS_GROUPS=assets assets:precompile'" on 106.187.36.187

This bug just appeared just out the blue . Have tried for hours so if anyone else knows how to fix , please save me.

Avatar

Thanks for this brilliant tutorial! I am new to rails and this one made a few pennies drop.

How can I achieve that destroying a question automatically destroys all associated answers records in the database?

Avatar

Como posso implementar utilizando coffeescript?
Por favor mostre exemplos do novo rails 3.2.X mais Highcharts
Estamos curiosos para saber como funciona na nova versão do rails.

Obrigado.

Avatar

DELETE /products/1/delete looks rather confusing, I think it is better to use POST verb in this case: POST /products/1/delete. Also, these are perfectly valid RESTful routes, there is nothing wrong with them.

I would also suggest to extend your routing DSL explicitly instead of patching Rails internal classes so that the modification is obvious for you and others. This will also avoid troubles with external engines that will expect default behavior.

ruby
# lib/delete_resource_route.rb
module DeleteResourceRoute
  def resources(*args, &block)
    super(*args) do
      yield if block_given?
      member do
        get :delete
        delete :delete, action: :destroy
      end
    end
  end
end

# config/routes.rb
require 'delete_resource_route'

Example::Application.routes.draw do
  extend DeleteResourceRoute
  resources :categories
  resources :products
  root to: 'products#index'
end
Avatar

Testing with capybara and rspec , there is a railscasts for that, called "How do I test". Great and simple stuff.

Avatar

I'm having issues deploying an app that is using this authentication method. It works fine on dev (mac) enviroment, however, it crashes on a Linux Ubuntu box.

I'm getting the following :

cache: [POST /users] invalidate, pass

Any idea ?

Thanks,
Ramos.

Avatar

Totally agree. Especially since "The training wheels came off"

Avatar

Hi Jay,

Sorry about that. Please follow these suggestions to figure out the problem.

Avatar

Abstracting the SQL into ruby removes server specific syntax from your code, lets a driver take care of specifics, and leaving you to deal only with intent. Besides, at the end of the day, you can still use SQL when you really need to. The question I ask myself is "do I want to switch contexts here?"

Avatar

Thanks Yoda! I have this problem and also my postgres installation is kind of weird so was all messed. but thanks to you i can narrow down the prob and its now fixed!

Avatar

Hi! Another great episode Ryan :)

I've just watched this (a little late I know) and after installing
oh-my-zsh I noticed that I lost access to the history on interactive ruby console and also rails console. I remember (maybe I'm wrong) that after I closed a rails console session, I was able to access the last commands via the arrow keys when a new session was started.

Is it me o oh-my-zsh can't handle this? Isn't a big deal, just curious if is it possible.

Thanks again :)

Avatar

Hey great video really appreciate it - trying to figure out how to get past these two errors, wondering if you could point me in the right direction:

  1. Rubber[INFO]: Transformation executing post config command: function error_exit { exit 99; }; trap error_exit ERR

  2. config : 'option forwardfor' ignored for proxy 'passenger_proxy_ssl' as it requires HTTP mode.

Here is my deploy.rb
http://pastebin.com/6CdCP7DY

and here is my rubber.yml file
http://pastebin.com/7tUcrMqF

Let me know if you need any additional info...thanks!

Avatar

Only thing I dislike about Heroku is the lack of Ruby 1.9.3 support

Avatar

Ok. I think I've finally figured it out. You have to wrap all of the query strings in plainto_tsquery, so wherever you have 'Lex Luthor', you need it to be plainto_tsquery('Lex Luthor').

So I have a scope called organization_name I use like this:

ruby
scope :organization_name, lambda { |term| { :conditions => ["to_tsvector('english', organization_name) @@ plainto_tsquery(:q)", q: term] } }

HTH

Avatar

Got mine from Cheap SSLs. I'm using Apache because the Ubuntu installations I've worked with have already had it ore-installed. My app is Rails 3.2 so all I did was put a config.force_ssl = true into my production.rb file.

Avatar

But he doesnt save the access token in this episode, only the provider and the uid

Avatar

Seems it is crashing out on our project.

[Notice] Detected Rails 3 application
Loading scanner...
[Notice] Using Ruby 1.9.2. Please make sure this matches the one used to run your Rails application.
Processing application in /home/**/projects/**
Processing configuration...
[Notice] Escaping HTML by default
Processing gems...
Processing initializers...
Processing libs...
Processing routes...

Processing templates...

Processing data flow in templates...
Processing models...

Processing controllers...

Processing data flow in controllers...
Killed7 controllers processed

Reaches 62/127 for data flow in controllers then hangs and dies.

Avatar

Very good!

Just one question: I saw in the end that it's possible to change app permission dinamically, is it possible to change app name too? It would be useful for I18n, I have an app that has a name associated to an idiom and another name for another idiom.

Avatar

FYI, I was getting an error when I ran the migration file that was asking to specify an extension version for hstore. Turns out I did not have the postgres contrib module installed. You need to that to add the hstore extension to the postgres db. On Ubuntu I did 'sudo apt-get install postgresql-contrib-9.1'.

Avatar

Hi,

I got 2 models, "User" and "Memberships". Each user has multiple memberships (has_many), and each membership belongs_to an user.

ruby
class User < ActiveRecord::Base
    has_many :memberships, :dependent => :destroyend
end
class Membership < ActiveRecord::Base
    belongs_to :user 
end

My question is: How do I loop thru each user and each membership? My idea was to build 2 loops, but its not working =/ (Unknown method 'each' for users?)

ruby
xml.instruct! :xml, version: "1.0" 
xml.rss version: "2.0" do
  xml.channel do
    xml.title "..."
    xml.description "..."
    xml.link users_url

    @users.each do |user|
      user.memberships.each do |membership|
        xml.item do
           xml.title membership.name
           xml.pubDate membership.subscribed_at.to_s(:rfc822)
        end
      end
    end
  end
end
Avatar

Great episode as always. One small question thought: What's the best way to handle validation? (Especially if you create multiple new records using jquery tokeninput)

Avatar

Hey did you ever find a solution to the heroku problems you were having? Have you seen this article on heroku? I was just about to implement delayed_job on heroku when I saw your post.

https://devcenter.heroku.com/articles/delayed-job

Avatar

It is not hard to make chef-server run redundantly.

Avatar

Thanks for that! I was wondering why they weren't update more often.

Avatar

In case someone is interested, the problem was due to Mac OS 10.7.3 in my case. They changed the DNS resolve order at some point and now at first place is not /etc/hosts but your local DNS server or something like that. So, production.foo.com is resolved as pointing to a real host using this domain name. I changed foo.com to something non-existent in several rubber config files to solve this problem. Also edited /etc/hosts to have the new domain name I am using.

Avatar

The "any attribute as a permalink" link in the Show Notes has a period following the URL in the href... (http://railscasts.com/episodes/63-model-name-in-url.)

Fortunately, I was able to figure it out, though maybe not so many people would be so lucky. :-)

Avatar

Hey, thanks for the comment. I've been playing around with chef using the hosted version. I realized that some of the opscode cookbooks are a bit outdated, so I've turned to github to find cookbooks. My problem now is how to mix these cookbooks with the ones I've already downloaded using knife cookbook install site install... I think Librarian should help, but I'm lost after you mentioned bundler. What does bundler have to do with chef?

Avatar

I'm stuck too with a similar issue : any gem added to Gemfile seems to not to be found by the application once deployed. This results in classes not found by autoload:

I, [2012-06-20T18:48:51.712022 #17056] INFO -- : worker=3 spawning...
I, [2012-06-20T18:48:51.723871 #15773] INFO -- : worker=3 spawned pid=15773
I, [2012-06-20T18:48:51.731071 #15773] INFO -- : Refreshing Gem list
E, [2012-06-20T18:48:51.868403 #15761] ERROR -- : uninitialized constant Refinery::Blog (NameError)
/home/deploy/apps/s2w_refinery/releases/20120620163007/config/initializers/refinery/blog.rb:1:in `'

Avatar

Does anybody have a good testing strategy for this?

Avatar

it happened to me

servers: ["my.com"]
[my.com] executing command
** [out :: my.com] cp:
** [out :: my.com] cannot create directory `/home/rails-apps/my-beta/releases/20120620085906'
** [out :: my.com] : No such file or directory
** [out :: my.com]

Avatar

I like it. I'm not sure if I agree with Jeremy Seitz, as I did something similar to Austin Schneider.

ruby
# presenters/post_presenter.rb
# Note the variable passed in to `present` is also the argument given to the block; this is intentional, see my explanation below.
<% present post do |post| %>
  <div class="<%= post.css_class %>">
    <div class="caption"><%= post.caption %></div>
    <div class="image">
      <%= image_tag(post.image_url) %>
    </div>
    <div class="description">
      <%= post.description %>
    </div>
    <div class="rating">
      <%= post.rating %>
    </div>
  </div>
<% end %>
ruby
class BasePresenter
  #...

  def method_missing(*args, &block)
    @object.send(*args, &block)
  end
end

In my view code, note that you can't tell the difference between post (as PostPresenter) and post (my active record model). I think the ambiguity is fine, or good actually; it's easy to read. To be able to do that, I overrode method_missing to point to the model. That way I don't have to use delegate. But this makes it a little easier to deal with when shifting code around via partials and not having to rename passed locals.

Avatar

Did you ever get an answer to your question? I'm having the same problem.

Avatar

The bullet-gem notifies you of eager loading SQL queries :)

Avatar

Thanks Ryan ....Anyone have a recipe for rmagik or imagemagik?

Avatar

Hey, thanks for the episode. After running the command below:

cap rubber:create_staging

I get the following error:

connection failed for: production.foo.com (Net::SSH::AuthenticationFailed: root)

Assuming that it has something to do with the fact that Ubuntu would not allow a root user to ssh by default I changed my config/deploy.rb file to use ubuntu as user. However, after that I get a similar error:

connection failed for: production.foo.com (Net::SSH::AuthenticationFailed: ubuntu)

Does someone have an idea about why this could be happening. I think it may be related to the ssh keys used but to me things seem ok with them.

Avatar

I ran into this same problem. Turns out that Ubuntu is deprecating the "admin" group in favor of the "sudo" group, as that's more consistent with the upstream implementation and Debian.

I found this is the Precise release notes at https://wiki.ubuntu.com/PrecisePangolin/ReleaseNotes/UbuntuDesktop

Avatar

Is any substitute for fancy_irb when im using pry instead of irb ??

Avatar

Nice episode - had a quick question though. If I wanted to add comments to the index pages eg Articles#index (rather than Articles#show) how would I set up the instance variables @commentable, @comments, @comment?

Avatar

Nothing wrong with this approach I think. Changing rails code is perfectly fine, though documented if necessary, I'd say. Nothing wrong with extending/improving rails itself. ;-)