RailsCasts Pro episodes are now free!

Learn more or hide this

Recent Comments

Avatar

Is it possible to use the attributes variable in the controller when using the scaffold generator? I would like to automatically generate two put actions 'up' and 'down' in my controller, if the generated resource has a position attribute. But I get an error saying it does not find the attribute variable. Any idea?

Avatar

I am on the same boat as Dave H, Ryan. I've looked online for ways to fix this but have come up with nothing. It would be awesome if you could address this if you had the time as it seems devise 2.0.4 is very different from the version used in this tutorial! This is the only devise screencast I've found and I'm sure many people new to rails would benefit from your clear explanations!

Avatar

Tried this, but no calendar shows up - I just get the Month Header with the FWD/BACK arrows to change the month. No data or even a blank calendar displays. There is data in my @schedules array.

<div id="calendar">
<h2 id="month">
<%= link_to "<", :month => (@date.beginning_of_month-1).strftime("%Y-%m-%d") %>
<%=h @date.strftime("%B %Y") %>
<%= link_to ">", :month => (@date.end_of_month+1).strftime("%Y-%m-%d") %>
</h2>
<% calendar_for(@schedules) do |t| %>
<% t.head('mon', 'tue', 'wed', 'thu', 'fri', 'sat', 'sun') %>
<% t.day (:day_method => :coursedate) do |day, schedules| %>
<%= day.day %>
<% schedules.each do |schedule| %>
<%= h(schedule.id) %>
<% end %>
<% end %>
<% end %>
</div>

Avatar

Daaamn Chef is serious. It doesn't even make sense to use it for the tiny one-server example you gave; it's power only really starts to make sense once you see how Chef Server works to let you implement an EC2-type setup on your own infrastructure.

I've seen the value of it for a long time, but two different attempts to ease into it were thwarted by the bad introductory materials. This is a great introduction. I look forward to using this as a jumping off point to actually get into Chef someday.

Thanks!

Avatar

Nokogiri does that by default when using the ::HTML call. You need to use .fragment

doc = Nokogiri::HTML.fragment(html)

Avatar

I really like the Capistrano recipes approach to deployment. But as configured, the deployment only works from the master branch on the github repo. What steps would need to be taken to deploy from another branch, i.e. a staging branch, onto a staging app on the same linode?

Avatar

Am using kaminari ajax pagination in my project. It is working fine, But contents are displaying number of pages times in the one page. For example if number of items per pages is 7, then it is displaying 7 times the same content (7 items). What am doing is

In product_details controller

  def index
    @products=ProductDetail.where("department_id = ? and category_id = ?",1, 1).page(params[:page]).per(15)
  end

In product_details/index.html.erb

<div id="product_details">
    <%= render @products %>
</div>
<div id="paginator">
    <%= paginate @products, :remote=>true %>
</div>

In product_details/index.js.erb

$('#product_details').html('<%= escape_javascript render (@products) %>');
$('#paginator').html('<%= escape_javascript(paginate(@products, :remote=>true).to_s)%>');

In product_details/_product_detail.html.erb

<div id="product_list">             
    <% @products.each do | product | %> 
        <div class="product_container">     
            <div class="product_box" >
                <div id="future_image_container">
                    <div class="image_block" >
                        <%= image_tag(product.image_path, :alt => "product image", :height=>"215px") %>
                    </div>
                    <span id="future_price" style="text-decoration: line-through; color: #9e9c9c;">
                        <span style="color: black;">
                            <%=  "$#{product.price}" %>
                        </span>
                    </span>
                    <div id="circle">
                        <p>
                            <% if(product.discount > 0) %>
                                <% new_price=((2.0*((product.price*product.discount)/100)).round)/2.0 %>
                            <% else %>
                                <% new_price=product.price %>
                            <% end %>
                            <%= "$#{new_price}"%>
                        </p>
                    </div>
                </div>
                <p class="future_product_name">
                    <%= product.name %>
                </p>
                <% @brands=Brand.where("id=?",product.brand_id)
                    @brands.each do |brand|
                        @brandname=brand.name
                    end
                %>
                <p class="future_product_name">
                    <%= "Brand : #{@brandname}" %>
                </p>
            </div>
        </div>
    <% end %>
</div>

Please help me to solve this problem

Avatar

I switched to RubyMine from VIM a while ago b/c the remote degugger is such a pain to inject every time using VIM/TEXTMATE/WHATEVER. Visual debugging is REALLY nice :) I'm not sure what technique they use, but debugging has worked on Ruby 1.9.3 for a while with RubyMine.

Avatar

Nice episode!

After you read the wiki at http://wiki.opscode.com/ to understand the basic commands and architecture of chef and maybe some of the available opensource chef cookbooks you probably want to check footcritic:

http://acrmp.github.com/foodcritic/

It's a quite new project that analyzes cookbook code regarding the best/common practice of writing chef cookbooks.

E.g. I see Ryan uses the (old) Ruby-symbol syntax to access node data. As far as I remember this was deprecated in favour of the typical 'string'-keys syntax: http://acrmp.github.com/foodcritic/#FC001

I hope, some day, the opscode guys will also provide an "official" tool that makes life with chef-solo easier without having to use 3rd party tools...

Until that, you may want to check:

https://github.com/matschaffer/knife-solo
or:
https://github.com/tobami/littlechef

Avatar

Does anyone know of a way to add translations on the fly as in say a user with admin rights creating a new locale?

Avatar

Timezone is not easy as it looks. Timezone-related code must be carefully written.

I tried to find an easy way to set Rails config.time_zone to local but failed.

Now I use an initializer:

ruby
# from rake task time:zones:local
jan_offset = Time.now.beginning_of_year.utc_offset
jul_offset = Time.now.beginning_of_year.change(:month => 7).utc_offset
offset = jan_offset < jul_offset ? jan_offset : jul_offset

offset = if offset.to_s.match(/(\+|-)?(\d+):(\d+)/)
           sign = $1 == '-' ? -1 : 1
           hours, minutes = $2.to_f, $3.to_f
           ((hours * 3600) + (minutes.to_f * 60)) * sign
         elsif offset.to_f.abs <= 13
           offset.to_f * 3600
         else
           offset.to_f
         end

ActiveSupport::TimeZone.all.each do |zone|
  if offset.nil? || offset == zone.utc_offset
    # use that timezone
    Rails.application.config.time_zone = zone.name
    break
  end
end
Avatar

Awesome railscast, as always. Does have any information on how to seed the translation table?

Avatar

That qualifies for »abandoned«, in my opinion ;-)

I had have also trouble to install ruby-debug19 on some Debian machines with Ruby 1.9.2 using either RVM or rbenv. debugger works like a charm :-)

Avatar

As always, good information. I use pry on a daily basis in both Rails and POR apps. Great tool for effective debugging.

Avatar

You'll want to provision the server(s) with Chef (or similar tools like Puppet) to prepare it for deployment. Then use Capistrano to do the actual deployment(s).

Avatar

I found out about
pry-nav

adding this to Gemfile:
gem 'pry'
gem 'pry-rails'
gem 'pry-remote'
gem 'pry-nav'

Avatar

Hi, I'm using pry and pry_debug in my rails application, have no problem at all with "rails console",but I can't figure out how to step when I include binding.pry in my controller. any hints please.

Thanks!

Avatar

Mixing capistrano and puppet/chef could be an option. As you said, creating users , installing packages and ensuring they stay installed are what tools like puppet/chef are made for. On the other hand configuring anything app specific i.e. nginx host, unicorn and so forth is easier using capistrano because it is more closely related to the application.

Avatar

Any tips for using debugger or pry with Pow?

Avatar

It's fixed now. Thank you for pointing this out.

Avatar

Answer: this is an additional syntax available in Ruby 1.9.

Avatar

In the users controller, the line

ruby
redirect_to root_url, notice: "Thank you for signing up!"

seems to be giving an error because of how the flash notice is assigned. It goes away when switched to this:

ruby
redirect_to root_url, :notice => "Thank you for signing up!"

Is this a typo or am I doing something else wrong?

Avatar

@dominik it's not really abandoned, it's just not being looked after as it should be. It's a huge pain to install on Ruby 1.9.3 due to gems not released to rubygems.org! Personally I think it was about time it was forked considering 1.8.7's death is preeminent and 1.9.3 has been GA for over 6 months.

Avatar

Hey,

I think chef is more for provisioning the server, I would still stick with capistrano for deployment.

Avatar

I am using bootstrap-sass.
But, after I assigned bootstrap variables to mine, I couldn't see the changes.

scss
$iconSpritePath: image_path('glyphicons-halflings.png');
$iconWhiteSpritePath: image_path('glyphicons-halflings-white.png');

$navbarBackground: #555;
$navbarBackgroundHighlight: #888;
$navbarText: #eee;
$navbarLinkColor: #eee;

$linkColor: #c52f22;
$linkColorHover: #980603;

@import "bootstrap";

body { padding-top: 60px; }

@import "bootstrap-responsive";
Avatar

Nice-to-know episode! Any idea, why ruby-debug19 was abandoned?

—Dominik

Avatar

Did you ever figure out what was going on there? I'm running into the same issue

Avatar

I've got require_tree . at the bottom (and everything else the same as your application.js file) however, I'm not able to get it to work. This is the error I'm getting in Firebug

Raffler.Routers.Entries is not a constructor
[Break On This Error]

new Raffler.Routers.Entries();

Avatar

I am wondering, if I use Integration testing, is functional testing necessary? And what about Acceptance testing? I am struggling to understand if you can stick to Integration testing and then just forget about Functional testing?

Thank you :)

Avatar

They are open source, so you can just patch them and submit a pull request :)

Avatar

How to use pry_debug in a rake file?

Avatar

How to use pry_debug in a rake file?

Avatar

So having covered Capistrano and Chef, can Chef be used without Capistrano for regularly deploying Rails apps? Does moving to Chef obviate Cap? I know I could find out myself but I'm really looking for confirmation that zsh history search for a long command is giving me less than these tools.

Avatar

Thanks for sharing, I wasn't familiar with Sunzi. I'll add it to the list of alternatives.

Avatar

Nice episode. There is definitely a steep learning curve with chef. Here are a couple of libraries that make it simpler:

  • Knife-Solo - This allows you to remotely install chef on a blank machine using knife prepare and also allows you to push your recipes to your remote server using knife cook.

  • Librarian - This works like bundler for chef recipes. You define a Cheffile and list out what cookbooks you need, and it will download them and their dependencies into your cookbooks directory. If you have custom recipes, it is good to move them into a site-cookbooks folder so they don't get overwritten by librarian when you import your cookbooks. When you're ready, you can go back to knife-solo to push them out to your server.

Avatar

Hello, great screencast..

I don't think it's a good manner to get the unicorn started by symlinked script in /etc/init.d, because the script which can be changed by deployer user is ran by root user at boot so it makes huge security vulnerability when the deployer user account is hacked throught the webapp..

Probably better would be to use some gem like whenever and get the init script started by the cron "every :reboot"

Avatar

What a great episode. Thnx Ryan.

I am a bit disappointed that most cookbooks ignore Mac OS X server. :(

Avatar

Brett, i fixed that by adding next line in pianos.rb file

ruby
attr_accessible :name, :dimensions, :manufactured_on, :upright, :photo_id, :description, :position
Avatar

Ryan,

chef-solo is cool, but it could be quite involving when your need is pretty simple.

With Sunzi, installing git-core on Linode is about 5 commands:

$ sunzi create
$ cd sunzi
$ sunzi setup linode
$ echo "apt-get -y install git-core" >> install.sh
$ sunzi deploy yourhost.com

Could you try that out? :)

Avatar

A quick FYI for others that are using engine yard instances. You will want to have redis running on a utility instance and if you follow EY's recommended chef recipe and implementation, add this to your split initializer:

# Load the redis.yml configuration file
redis_config = YAML.load_file(Rails.root + 'config/redis.yml')[Rails.env]

# Connect to Redis using the redis_config host and port
if redis_config
  $redis = Redis.new(:host => redis_config['host'], :port => redis_config['port'])
end

if $redis
Split.redis = $redis
end

Split.configure do |config|
config.db_failover = true # handle redis errors gracefully
config.db_failover_on_db_error = proc{|error| Rails.logger.error(error.message) }
# config.allow_multiple_experiments = true
end

Avatar

If you use bootstrap-sass gem, does it have the same generators and what not as the twitter-bootstrap-rails gem?

Avatar

I figured it out the issue. I deleted public/assets directory generated by
RAILS_ENV=production bundle exec rake assets:precompile
for deploying assets to heroku

Avatar

Everything went ok but suddenly I'm having this error:

js
window.Widget =
  Models: {}
  Collections: {}
  Views: {}
  Routers: {}
  init: ->
    new Widget.Routers.Listings()
    Backbone.history.start()

$(document).ready ->
  Widget.init()

Uncaught Error: Backbone.history has already been started

what could be wrong ? I checked indentation and it seems ok.
Thanks
Aldo

Avatar

For using this with associations I found the following worked for me (I am displaying a list of transactions, the association is a category). In my Transactions controller:

ruby
  def index
    if params[:sort] == "category"
      @transactions = sort_by_category
    else
      @transactions = sort
    end
  end
  
  private
  
    def sort
      current_user.transactions.order(sort_column + " " + sort_direction).page(params[:page])
    end
    
    def sort_by_category
      current_user.transactions.paginate(
            :page => params[:page],
            :include => :category,
            :order => "categories.name #{sort_direction}")
    end
  
    def sort_column
      Transaction.column_names.include?(params[:sort]) ? params[:sort] : "date"
    end
  
    def sort_direction
      %w[asc desc].include?(params[:direction]) ? params[:direction] : "desc"
    end

I'm paging the results with will_paginate but if not paging something along the lines of the following would work I believe:

ruby
current_user.transactions.find(:all, :include => :category, :order => "categories.name #{sort_direction}")
Avatar

Apparently there’s only a significant advantage in performance if you’ve got fast clients, otherwise the opposite is the case: http://www.ruby-forum.com/topic/1822610

Avatar

Hi.. I am working with geocoder.
In my model, i am having fields like location, city, state, country and Pin code/ Zip code..
With the help of Geocoder i could be able to locate the complete address including street, city, state and country.

But my requirement is i need to locate the place with the help of Zip code too...

Here is my model:

class Employee < ActiveRecord::Base
attr_accessible :name, :location, :city, :state, :country, :pincode, :latitude, :longitude
def address
[location, city, state, country].compact.join(', ')
end
geocoded_by :address
after_validation :geocode, :if => :location_changed?
end

Can anyone help me out????????????

Avatar

I just used straight ejs instead of eco.
It means the template looks more like:

//index.jst.ejs

<h2>Entries</h2>
<ul>
  <% for(i=0; i<entries.length; i++){ %>
    <li><%= entries.models[i].get('name'); %></li>
  <% } %>
</ul>

It now works for me. But no nice coffee script templates.