RailsCasts Pro episodes are now free!

Learn more or hide this

Recent Comments

Avatar

Thanks. I had trouble getting that less theme to work, so I just decided to make my own css theme based off of the facebook theme. I put it on github if anyone else would like to give it a try:
https://github.com/fw-coder/jQuery-TokenInput-Bootstrap-CSS-Theme

You just set the theme to facebook and drop in this css file in place of the facebook css file.

Avatar

Has anyone one tried to build associations, with nested resource with frienly_id and having difficulties, and if so, how did you go about solving it?

ruby
#user model
 User < ActiveRecord::Base
  has_one :user_detail

  extend FriendlyId
  friendly_id :username #not slugged, a model column, created with user!

#user_detail model
 UserDetail < ActiveRecord::Base
  belongs_to :user
  
 validates :user_id, presence:true #not attr_accessible.

 #in routes
 resources :users, :path => ''
 resources :users, :path => '', only: [] do
   resource :user_detail, only: [:edit, :update]
end

I've tried everything I could think of to get post requests to work on edit action for user_detail. I've also tried not nesting the the user_detail, still no cigar!

Avatar

Has anyone tried to build associations with friedly_id and having difficulties, and if so, how do you go about solving it?

ruby
User < ActiveRecord::Base
 has_one :user_detail
extend FriendlyId
  friendly_id :username


UserDetail <<ActiveRecord::Base
 belongs_to :user

Based on that i

Avatar

Thanks for the valkyrie tip - I've started using it - super fast and simple.

Avatar

You can also add

feed.icon '/assets/icons/feed.gif'

For the atom feed, does anyone know how to add an image for each article? I've seen some websites that do that.

Avatar

if some one else has a problem with create.js using rails 3.2 you need to change the controller action create

ruby
  def create
    @message = Message.create!(params[:message])
    redirect_to :action => 'create', :format =>'js'
  end
Avatar

It would be great to make a screencast about rate limiting.

Avatar

Very nice implementation!
Could be even better if you implemented it somehow with your nested_form and made it dynamic. Do you have a tip on how to make it work with nested_form?
thanks!

Avatar

Brett, I used:

drops_datatable.rb
if params[:sSearch].present?
  drops = drops.where("items.name like :search or characters.name like :search", search: "%#{params[:sSearch]}%")
end

Nested routes took me a little longer to get working.
eg.

routes.rb
resources :characters do
  resources :drops
end

When I went to /characters/1/drops, I was getting the full list of drops.

The index action was being called twice and then fetch. On the first call, the index action had all of the parameters, but params didn't have the character_id on the subsequent call to index or the call to fetch.

To resolve that, I changed the table tag in my view code to:

drops/index.html.haml
%table#dropsTable{:data => {:source => "#{ drops_url(params.merge!(format: "json")) }"}}
Avatar

I was using a previous aws key-pair and for some reason creating one named gsg-keypair fixed the problem.

Avatar

Yeah I have the same problem despite the instance being available. I'm able to ssh to it.

bash
. ** Failed to connect to IP_SNIP, retrying
  * executing `rubber:_allow_root_ssh'
  * executing "sudo -p 'sudo password: '  bash -l -c 'cp /home/ubuntu/.ssh/authorized_keys /root/.ssh/'"
    servers: ["SNIP"]
Avatar

Is there a reason rubber uses haproxy and not the Amazon Load Balancer? Are there any benefits from using haproxy and is it possible to use the Amazon Load Balancer with rubber?

Avatar

Solved

The problem was on my end. One of the gems my app depends on was overriding the String#constantize method, and it was breaking the resolution of the routing namespace. Removing that gem fixes my problem.

Sorry for the bother.

Avatar

i've solved it thanks. Thanks to Raison D'souza's comment

Avatar

For some reason I can't get my app to work based on the sample code for this screencast. After setting up the routes, api_constraints, and the api/v1/ controller directory structure, API requests fail with the exception:

console
ActionController::RoutingError (wrong constant name v1):
  app/controllers/api/v1/base_controller.rb:3:in `<module:V1>'
  app/controllers/api/v1/base_controller.rb:2:in `<module:Api>'
  app/controllers/api/v1/base_controller.rb:1:in `<top (required)>'
  app/controllers/api/v1/groups_controller.rb:1:in `<top (required)>'

My controller at app/controllers/api/v1/groups_controller.rb looks like this:

ruby
module Api
  module V1
    class GroupsController < ApplicationController
      respond_to :json

      # ... snip ....

    end
  end
end
end

My Routes look like this:

ruby
  # ... snip ... 
  namespace :api, defaults: {format: 'json'} do
    scope module: :v1, constraints: ApiConstraints.new(version: 1, default: true) do
      resources :groups
    end
  end
  # ... snip ... 

Anyone else have this problem? Have I missed something?

Avatar

Hi I keep getting:

NoMethodError in SessionsController#create
undefined method `[]' for nil:NilClass

This appears after I logged into Twitter and before redirecting back to the callback page.

Avatar

Ryan,

As mentioned above my resources are nested. I would suggest one change:

resource, id = request.path.split('/').last(2)

Avatar

I have been working on a similar system except that mine is more complex because i have nested resources. I can't get past the first level of nesting with the polymorphic path in the form_for.

For example I have something like this:

Locations with many Building with many Rooms. I want to comment on each with the polymorphic relationship but the system fails when you try to comment on a Building Rails throws an exception looking for 'building_comments_path' but the routing table generates 'location_building_comments_path'.

I am at a loss to generate the polymorphic path on the fly. I could manually generate the routes or the path in my controllers but I figure there has to be a better solution.

Avatar

Thanks for the update Ryan. For some reason my html was being interpreted as plain text and escaped so had to add this:

ruby
entry.content safe_markdown(post.content).html_safe, :type => "html"
Avatar

And I finally found a solution for it. Not a solution, THE solution :-)

You'll have to require your dependencies in the gem's initialization file and then it will work like a charm. I think Ryan would say "Yay" ;-)

Example as image

Avatar

Hi, im getting "Can't mass-assign protected attributes" error.
I googled the problem so i added attr_accessible but it doesnt work anyways...Any ideas?

Thanks

Avatar

thank you, somehow it didn't work with filtering, but I used

@medical_consultation.medicine_ids = [] unless params[:medical_consultation][:medicine_ids].present?

directly in update and create action and now it works nice.

Avatar

When I tried Geocoder, I found the query results were not accurate and I didn't have time to look into them. I submitted a suggestion on this.

Avatar

Struggling on getting the validations setup properly.. Im using devise, so the user sign up page begins with: email, password, password confirmation witch are all handled and validated by devise.. Now im getting a

"NoMethodError in RegistrationsController#create".. undefined method `include?' for nil:NilClass"

after following the steps in that wicked tutorial exactly.. any ideas? Thanks

Avatar

While deleting bootstrap.js.coffee stops the error, it also makes it so those Bootstrap features won't be available in your application.

ruby
//= require jquery
//= require jquery_ujs
//= require twitter/bootstrap
//= require bootstrap
//= require_tree .

The key is to add the "twitter/bootstrap" before the "bootstrap". Then the functions should be available. Check your page source in development mode to verify that a number of bootstrap js files get included.

Avatar

Would it be possible to pull dates from 2 different models in the same calendar? .. For example, I have a holidays table and a birthdays table and would like to have 1 calendar display both..

Avatar

I like using the idea of using the Accepts header for versioning, although it does make it harder to test API versions from a browser's URL bar.

But there's a bug in this code that will be exposed once you reach v10. matches?(req) will return true when the router asks if the request is for v1, because 'application/vnd.example.v10'.includes?('application/vnd.example.v1') is true.

One way to fix this is to reverse the order of your routes file: put newer versions at the top, not at the bottom.

Avatar

Did you solved the issue? I've got the same problem (jquery, bootstrap) and the solution or "fix" presented in your linked thread isn't that satisfactory, is it?

Avatar

Great episode as always. I'm a newb and working on my first app which will require real-time chat for users. I may be asking the wrong question here, but how would you go about private pub allowing a logged in user to display their name in the channel. Things could get messy with more than two users.

Thanks for your hard work!

Avatar

I haven't tried yet, but it might work, I thinkg you just need to enable before filters for your API controllers.

Avatar

There are few forks out there, but we're working in a branch for that. :-)

Avatar

Hi Anket, I have a same problem over here.

Avatar

This is working great for me except for one issue. I have SEVERAL nested models.

A workout has_many steps, a step has_many actions, an action has_many instructions. When I click to add a new step, I would like that step to be populated with on action fieldset, and that action fieldset, populated with one instruction fieldset. But it just renders the empty step fieldset, I have to click the "add action" and then the "add instruction" buttons for those to render. Does anyone know how to get all the nested fieldsets to render when I add a step?

Data Associations:

  • Workout

has_many steps

  has_many actions

     has_many instructions
Avatar

I just noticed that too, Unicorn doesn't seem to start again after a server reboot even though it should, according to rcconf: http://minus.com/mbElBG9hS/

This is the last bit of config I need, I really don't feel comfortable having to manually start unicorn after a reboot, any help would be greatly appreciated :)

Avatar

Thanks for this information. Will be taking a closer look at this.

Avatar

By the way API::V1::ProductsController will not just work.

Avatar

Is it possible to use rails-api and doorkeeper together? I'm not sure where the Doorkeeper UI should live. Possibly hack it into rails-api or add it to another rails app, what do you think?

Avatar

Has anyone got Doorkeeper working with Mongoid?

Avatar

I dont know how about you guys but i cant seem to get my tests to work.
How do you guys write these tests if your controller is nested inside the modules?

ruby
require 'spec_helper'
namespace :api do
  namespace :v1 do
    describe ProductsController do

      describe "GET 'index'" do
        it "returns http success" do
          get 'index'
          response.should be_success
        end
      end
    end    
  end
end
console
Failures:

  1) ProductsController GET 'index' returns http success
     Failure/Error: get 'index'
     ActionController::RoutingError:
       No route matches {:controller=>"products"}
     # ./spec/controllers/api/v1/products_controller_spec.rb:10:in `block (5 levels) in <top (required)>'

Obviously because the correct route should be:
{:action=>"index", :controller=>"api/v1/products"}

Avatar

See Two-factor Authentication with Rails and the subsequent Using the Google Authenticator App with Rails for tutorials of using 2-factor authentication with Google Authenticator.

Avatar

Here's an example of how to use the password grant type without a callback URL...

text
curl -i http://localhost:3000/oauth/access_token \
  -F grant_type=password \
  -F client_id=<client id> \
  -F client_secret=<client secret> \
  -F "scope=<scope>" \
  -F username=email@address.com \
  -F password=password
Avatar

So I followed the episode exactly and I'm getting 404 errors for anything in my public folder? Any ideas why...

Stack
nginx 0.7.65
unicorn
rails 3.2.3
Ubuntu 10.04
rvm latest
ruby 1.9.3-p194

I know about the rails config option to serve_static_assets, but wouldn't I want nginx to do that?

Avatar

Actually, if you look at existing apps that authenticate through Twitter's oAuth for example, you can see that, indeed, a browser is required to grant access to the account. However, both iOS and Android have an option to launch a browser window within an application itself.

So usually when the users clicks "login through twitter", you'd fire up a browser screen inside the app that will load the Twitter authentication page. This page is already optimized for mobile so it will simply show the button to authenticate (or the login fields if the user isn't logged in to twitter yet). Then you have your app setup to close the webview when a succesful request is made, and log the user in.

Facebook is a similar example, except that in this case, facebook requires the app to actually launch the Facebook app, which will handle the authentication and automatically switches back to your app when the authentication is succesful.

Avatar

Hi Ryan, lately I've seen a lots of development railscasts for rails API's. What are the best practices to test API's and versions? Because you don't want to break anything down if you implement new features, change the json format later on. What i would like to know is how you guys test your json api's input and output and even with versioning. Maybe this would be a good idea for a railscast.

Thanks