RailsCasts Pro episodes are now free!

Learn more or hide this

Recent Comments

Avatar

Sidequestion: Is it better to load modules into my models? I currently use abstract models for most things (which, however, loads modules itself). But I runned into problems as the self.abstract_class = true gotcha seems to be not widely known...

Avatar

I've spent hours trying to get Chosen to work and have posted question on Stackoverflow with no luck--including necessary lines in application.js, application.css, and adding the appropriate coffeescript. I'm using Bootstrap and think that may be getting in the way. Are there any css directories I should be clearing out? Thanks!

Avatar

Hey guys,

I followed the tutorial precisely but I am getting an error such as this:

NoMethodError in SessionsController#create

ruby
undefined method `slice` for nil:NilClass

Rails.root: /Users/raybesiga/Documents/Sites/foodie
Application Trace | Framework Trace | Full Trace

app/models/user.rb:29:in from_omniauth'
app/controllers/sessions_controller.rb:3:in
create'

However my user.rb file is as below:

ruby
class User < ActiveRecord::Base
  # Include default devise modules. Others available are:
  # :token_authenticatable, :confirmable,
  # :lockable, :timeoutable and :omniauthable
  devise :database_authenticatable, :registerable,
         :recoverable, :rememberable, :trackable, :validatable

  # Setup accessible (or protected) attributes for your model
  attr_accessible :name, :email, :password, :password_confirmation, :remember_me, :provider, :uid
  validates_presence_of :name
  validates_uniqueness_of :name, :email, :case_sensitive => false
  # attr_accessible :title, :body

  def self.from_omniauth(auth)
    where(auth.slice(:provider, :uid)).first_or_initialize.tap do |user|
      user.provider = auth.provider
      user.uid = auth.uid
      user.name = auth.info.name
      user.oauth_token = auth.credentials.token
      user.oauth_expires_at = Time.at(auth.credentials.expires_at)
      user.save!
    end
  end
end

and my sessions_controller.rb file is as follows:

ruby
class SessionsController < ApplicationController
        def create
                user = User.from_omniauth(env["ominauth.auth"])
                # session[:user_id] = user.user_id
                session[:user_id] = user.id
                redirect_to root_url
        end

        def destroy
                session[:user_id] = nil
                redirect_to root_url
        end
end

Any idea why I get this error?

Avatar

I have a problem with will_paginate and sortable links. Since they are relative link, once I've update my partial after an edit or delete action the link includes the item ID like http://url/id?page=2 instead of http://url?page=2.

Can somebody help me solve it?

Avatar

Hi, I had the same problem. I deleted the bootstrap.js.coffee and it made my Bootstrap features unavailable. I tried to include the the "twitter/bootstrap" before the "bootstrap" and the following error occured "couldn't find file 'twitter/bootstrap'". Do you know what that can be about?

Thanks!

Avatar

Could you simply make an if statement around your stylesheet_link_tag?

Avatar

Is there any idea not to select the name that is already choosen in token input? for example In first i select mango when i search for m. Next time again when i search for m Mango should not be displayed as mango is already choosen. Is there any idea?

Avatar

I solved this by adding bundle exec like:

bundle exec cap deploy:setup

Avatar

Two things to make sure:

  • Your user "deployer" has all the lovely rbenv PATH stuff in place and working.
  • If that is all working, I posted an answer to your SO question that might help that involves changing the way you specify what user the start command runs as.

Hope that helps.

Oh, also su to your "deployer" user and run the magical "rbenv rehash" command? Dunno, just a thought.

Avatar

I find that "reload!" is extremely useful in the rails console when doing development; it reloads your environment, so it should pick up any changes you make to your source files.

Avatar

Don't make the mistake of setting tweet_id's type to an integer. MySQL maxes out at 2147483647 unless you specify a limit. It's easier to just make it a string.

Avatar

Anyone know if it's possible to control which predicates are available to the user in the dropdown? I'd like to only let my users choose from a few.

Avatar

I had this problem too. Before, my queries looked like:

`where("to_tsvector('english', title) @@ :q", q: query)`

to fix it:

`where("to_tsvector('english', title) @@ plainto_tsquery(:q)", q: query)`
Avatar

There is known issue with Windows and Python https://github.com/cowboyd/libv8/issues/29

in case you are seeing this error:

Installing libv8 (3.3.10.4) with native extensions
Gem::Installer::ExtensionBuildError: ERROR: Failed to build gem native extension.

d:/RailsInstaller/Ruby1.9.3/bin/ruby.exe extconf.rb
*** extconf.rb failed ***
Could not create Makefile due to some reason, probably lack of
necessary libraries and/or headers. Check the mkmf.log file for more
details. You may need configuration options.

Provided configuration options:
--with-opt-dir
--without-opt-dir
--with-opt-include
--without-opt-include=${opt-dir}/include
--with-opt-lib
--without-opt-lib=${opt-dir}/lib
--with-make-prog
--without-make-prog
--srcdir=.
--curdir
--ruby=d:/RailsInstaller/Ruby1.9.3/bin/ruby
Checking for Python...Unable to build libv8: Python not found!

Avatar

It appears that this was an issue with console.log, which I now realize wasn't intended to be in the final version of the code. When IE's "F12 Developer Tools" feature was enabled, the dynamic select menus worked as intended. I removed both instances of console.log from the coffeescript file and the issue is gone, with and without F12 Developer Tools enabled. Gotcha on me.

More on this here: http://stackoverflow.com/questions/11346091/i-e-craches-my-js-script-at-first-then-i-press-f12-and-it-works-beaultifully?lq=1

Avatar

I'm getting a

failed: "sh -c 'cd /home/deployer/apps/angel_list_api_research/releases/20120827050009 && bundle install --gemfile /home/deployer/apps/angel_list_api_research/releases/20120827050009/Gemfile --path /home/deployer/apps/angel_list_api_research/shared/bundle --deployment --quiet --without development test'" on 198.58.96.39

Has anyone any idea what this is trying to tell me?

Avatar

And the html...

html
<div class="row" id="preferred_performance_row">
  <select id="order_preferred_performance_id" name="p">
    <option value=""></option>
    <option value="1">Friday, 11/23/2012 -  2:00 pm</option>
    <option value="2">Friday, 11/23/2012 -  5:30 pm</option>
  </select>
</div>
<div id="preferred_ticket_level_row">
  <select id="order_preferred_ticket_level_id" name="tl">
    <option value=""></option>
    <optgroup label="Friday, 11/23/2012 -  2:00 pm">
      <option value="1">Orch 1 - $66.00</option>
      <option value="2">Orch 2 - $46.00</option>
    </optgroup>
    <optgroup label="Friday, 11/23/2012 -  5:30 pm">
      <option value="3">Orch 1 - $66.00</option>
      <option value="4">Orch 2 - $46.00</option>
    </optgroup>
  </select>
</div>
Avatar

This isn't working for me in Internet Explorer 9...Changing the first select menu doesn't do anything. The second select menu remains hidden.

Chrome on Windows, and Safari, Firefox, and Chrome on OS X work fine. Any gotchas that you've found?

coffees.js
jQuery ->
  loaded_ticket_level = $('#order_preferred_ticket_level_id :selected').text()
  if loaded_ticket_level.length < 1
    $('#preferred_ticket_level_row').hide()
  
  ticket_levels = $('#order_preferred_ticket_level_id').html()

  console.log(ticket_levels)
  $('#order_preferred_performance_id').change ->
    performance = $('#order_preferred_performance_id :selected').text()
    escaped_performance = performance.replace(/([ #;&,.+*~\':"!^$[\]()=>|\/@])/g, '\\$1')
    options = $(ticket_levels).filter("optgroup[label=#{escaped_performance}]").html()
    console.log(options)
    if options
      $('#order_preferred_ticket_level_id').html(options)
      $('#preferred_ticket_level_row').slideDown("fast")
    else
      $('#order_preferred_ticket_level_id').empty()
      $('#preferred_ticket_level_row').hide()
Avatar

That feature was released with active support 3.2. Try to update it!

Avatar

When I try to start up my rails (oauth client) app after building my OAuth strategy (identical to Ryan's structurally), I get this error:

undefined method `uid' for OmniAuth::Strategies:Module

Anyone seen this error before? I'm having a hard time figuring out what I'm doing wrong.

Avatar

If you add this to the model, then these items will no longer appear on your dropdown list.

ruby
  UNRANSACKABLE_ATTRIBUTES = ["first_name", "updated_at"]

  def self.ransackable_attributes auth_object = nil
    (column_names - UNRANSACKABLE_ATTRIBUTES) + _ransackers.keys
  end

However, if you remove exclude an item using the list above, it will no longer become sortable.

Avatar

Hi, does anyone knows how to accomplish that routing process in Rails 2.3.X ?
Thank you.

Avatar

Indeed, I had flashbacks to my programming languages class. By flashbacks, I mean shots of adrenaline and joy.

Avatar

Hey guys i am getting this error:

   command finished in 6676ms
  * executing `deploy:start'
  * executing "/etc/init.d/unicorn_default start"
    servers: ["10.0.14.17"]
    [10.0.14.17] executing command
 ** [out :: 10.0.14.17] sh: /etc/init.d/unicorn_default: not found
    command finished in 126ms
failed: "sh -c '/etc/init.d/unicorn_default start'" on 10.0.14.17

any ideas?

this is at the cap deploy:cold step

Avatar

I'm not sure if it's exactly the same thing, but what really saved me (for what I needed) was this https://github.com/moo-li/Simple-parent-child-forms-in-Rails-3.1

Great railcast anyways!

Avatar

I'm not sure if it's exactly the same thing, but what really saved me (for what I needed) was this https://github.com/moo-li/Simple-parent-child-forms-in-Rails-3.1

Great railcast anyways!

Avatar

After, pulling my hair for a few hours, this is how I am testing it:

ruby
it 'does not creates a new subscription if stripe fails to create a token' do
  exception = Stripe::InvalidRequestError.new("",{})
  Stripe::Customer.should_receive(:create).and_raise(exception)
  expect {
    post :create, subscription: valid_attributes
  }.to change(Subscription, :count).by(0)
end

The tricky part was creating the exception, I had to take a look at this

Avatar

Hello everybody,
I need to remove all searches from my database every 10 minutes...
So this would be the path
http://nameofmysite.heroku.com/search/1

How would you write the right code to do it?

Thanks

Avatar

add the following to the top of your config/deploy.rb

require "bundler/capistrano"
set :default_environment, {

'PATH' => "$HOME/.rbenv/shims:$HOME/.rbenv/bin:$PATH"
}

Avatar

Maybe I am over complicating this with gon? I can just render it directly with json and use the GET method in Fullcalendar?

Avatar

I am going to respond to your comment assuming that you are a true beginner. If I am saying something you already know or find the tone of my response offensive then I am sorry, I am only trying to help.

Before I continue to answer your comment I ask you to please not type messages in all-capitals, it appears as if you are shouting and comes across quite rude. Also saying things like "you must help me or I will go insane" doesn't inspire others to help you out, its more likely that you'll get ignored. No matter how desperate you are, if you want someone's help the best thing to do is to be polite and clearly explain your problem and adding as much relevant information as possible. You will find that this applies to communications on most tech resources (mailing lists, forums, etc.)

Now on to your problems:

I'm afraid you made a beginner's mistake, running rake db:setup will setup a fresh database, so that's what happened (that's a standard rake task in Rails). If you ran that command on your production environment the only thing you can do is restore your latest database backup. If you don't have a backup there's really nothing that can be done.

As for the template missing error, its hard to say without knowing your codebase. If you've been editing code on your production system (which you really shouldn't be doing, development should be done on in its own place, for example on your own machine) you will have to debug the error and fix it.

I hope that my reply gives you some insight into your problems.

Avatar

How did you expose your events to Fullcalendar? did you pass the json with gon or as an array? I have my events passed with gon sitting in window.gon but I have no idea how to set it into events:[

Avatar

Great Railcast. There seems to be a problem rendering the nested model fields when implementing this solution with models that have a one-to-one association. One-to-many associations show nested model fields fine, but not one-to-one.

Avatar

OK, EHM how can i start:

im newb, but:

I followed your instructions and after i started 'rake db:setup ' MY WHOLE WEBSITE BROKES APART!!! WHAT THE HELL HAPPENEND??? I CANT EVEN SIGN IN OR UP TO ME WEBSITE AND I GET "TEMPLATE IS MISSING" AND WHEN I LOOK IN PGADMIN ALL COLUMNS ARE GONE. YOU HAVE TO HELP ME OR I WILL GO INSANE I SWEAR

Avatar

I believe it's logically equivalent to this a = a ? a : "something"

Which means:
set the value of a to, if there is an 'a', then a, otherwise set it to "something"

Avatar

I ended up doing this, doesn't look elegant, but it works.

ruby
  ActiveAdmin.routes(self)
  
  
  get '/admin/episodes/:id', :controller => "admin/episodes",
      :action => 'show', :id => /[0-9]+\/[0-9]+\/[0-9]+/
  get '/admin/episodes/:id/edit', :controller => "admin/episodes",
          :action => 'edit', :id => /[0-9]+\/[0-9]+\/[0-9]+/
  put '/admin/episodes/:id', :controller => "admin/episodes",
              :action => 'update', :id => /[0-9]+\/[0-9]+\/[0-9]+/
  delete '/admin/episodes/:id', :controller => "admin/episodes",
              :action => 'destroy', :id => /[0-9]+\/[0-9]+\/[0-9]+/
Avatar

<%= form_tag projects_path, :method => 'get' do %>
you need an equal sign for rails 3
<%=
instead of
<%

Avatar

It seems they are thread-safe since they rely on Thread.current: directly from guides.rubyonrails.org

The locale can be either set pseudo-globally to I18n.locale (which uses Thread.current like, e.g., Time.zone) (...)

Avatar

Great screencast. I really like ImageMagick, here are some great examples of some stuff you can do if you're new to the library: http://imagemagick.org/Usage/

Avatar

Guys, I ran into an issue with Monit + Resque + rbenv setup. My Resque workers fail to start with Monit saying rbenv: not found, but the same command works fine if I run it directly in console under user deployer. Have someone managed to set up monit to monitor Resque workers? Any ideas?

I've posted some more info here: http://stackoverflow.com/questions/12094311/managing-resque-workers-with-monit-on-rbenv-setup

Avatar

I have sort of got it.

faqs_for_user = params[:faq].map{|x| x.to_i} & current_user.faq_id_list
faqs_for_user.each_with_index do |id, index|

The faq_id_list returns a list of id's that are allowed to be sorted. The procedure relies on the fact that the array intersection function returns items in the same order as the first parameter. (gulp)

If anyone has anything better here, would be good to see it.

Avatar

Anyone done anything with this & update_all where the items being sorted have a user_id parent. As it is, a Post with a random set of Faq's could resort regardless of who the parent user_id is.

Avatar

I set the position to Time.now.to_i as a default. You don't need to know a max position or reference the database to place it at the bottom of the list.

Avatar

Awesome. Why don't you wrap your calendar helpers into gem?

Avatar

I initial had some trouble implementing this together with Mongoid. It turned out that the problem was in the mongoid.yml configuration file. When I changed

host: localhost

to

host: 0.0.0.0

Everything worked properly. I guess this is because having a proxy server messes with the meaning of localhost.

Avatar

get rid of your watu_table_builder gem