RailsCasts Pro episodes are now free!

Learn more or hide this

Recent Comments

Avatar

I would also love to see Torquebox covered in an episode. I do have some experience with jRuby and concur with Martin. I would not use it for development purposes for the reasons that he mentions above.

jRuby is for deployment and integration with the Java world. It can be deployed on Tomcat which is the most widely used open source Java Server. As a matter of fact, Torquebox uses a customized Tomcat. Swing UI capabilities do seem promising though I have not written a Swing application in more than ten years, so I cannot comment on it.

All in all, a solid option for introducing Ruby in a Java entrenched enterprise.

Great work Ryan, appreciate the effort.

Avatar

Hi everyone.

Does anybody know how to update assets in existed app to use new bootstrap features?

Avatar

You forgot to delete the default site from nginx.
There are two options:
1. Do it manually:
the commands you have to enter:
ssh_to_your_server:
ssh deployer(or_which_user_u_have_on_server)@server_ip

commands_on_server:
sudo rm /etc/nginx/sites-enabled/default
sudo service nginx restart

to autostart it when server restarts:
sudo update-rd.d unicorn_yourapp_name

Or compare your nginx.rb script to (at minute: 7:27):
nginx.rb from RyanB

if its correct run: cap deploy:install

Avatar

Also check torquebox, I'm using it on a project right now and i'm really impressed. Problem though with jruby is slow startup time, so for example asset pipeline is unusable (compiling twitter bootstrap takes about 30s in dev on my mbp), also rspec takes longer to boot so tdd is quite painful.

Avatar

Ryan did not mention this explicitly, but it might not be obvious to some: You do not have to "deal" with Capistrano + JRuby 1.7 issues (Highline, SSH Forwarding). It's perfectly fine to use MRI while invoking the cap commands on your machine, you "only" need JRuby on the remote server where Trinidad lives.

One might also consider using the current "stable" version of JRuby on production 1.6.7 if you run into any specific issues with 1.7 (it's still a preview version although pretty stable).

Avatar

I second this one! While trinidad is kind of like the first step, the logigac next one is using a whole application server like jboss / torquebox.

Avatar

Trinidad is fantastic but do you plan or have considered an episode on Torquebox? (http://torquebox.org)
It has messaging, websockets, cluster, and many other awesome features!

Avatar

no, Unicorn (similar to Mongrel) uses some native code thus it won't compile on JRuby.

Avatar

Is unicorn compatible with jruby ??

Avatar

Let's say that your_extra_param should be the value of a second text field (you have categories and products and you want to autocomplete the products associated only with the selected category).

How can you make it work? Unfortunately I cannot figure it out.

Thanks.

Avatar

Anybody know why this happen ?

 ** Instance production created: i-219f8421
Waiting for instances to start..................
 ** Instance running, fetching hostname/ip data
  * executing `rubber:_allow_root_ssh'
  * executing "sudo -p 'sudo password: '  bash -l -c 'cp /home/ubuntu/.ssh/authorized_keys /root/.ssh/'"
    servers: ["54.248.63.94"]
.... ** Failed to connect to 54.248.63.94, retrying
  * executing `rubber:_allow_root_ssh'
  * executing "sudo -p 'sudo password: '  bash -l -c 'cp /home/ubuntu/.ssh/authorized_keys /root/.ssh/'"
    servers: ["54.248.63.94"]
Avatar

Hi, could you write down more about how to 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. I am totally new to this stuff. thx

Avatar

Ryan for a regular Rails application you think be better run it over jRuby in production?

Avatar

Thanks, Ryan. This is still a great intro to rails templates about 3.5 years after you originally "cast" it. I'm using rails 3.2 and found that the load_template you use to load the base.rb into authentication.rb is depreciated. The current Thor equivalent is apply. That might be useful to your more recent users.

Best,
Ben

Avatar

Now it works, it was a routing problem.

Avatar

Never mind, typo in the partial file name......

Avatar

I still maintain that you should be able to delete records in Rails by default when Javascript is not available, I've been banging on about this since 2006:

I must get around to implementing it as an Engine. I find it frustrating that you have to include the whole of jQuery on an app that doesn't otherwise require Javascript, just to let users delete records.

p.s. loving the Pro and Revised episodes Ryan!

Avatar

As written, the routes.rb file has something like this:

config/routes.rb
get "log_out" => "sessions#destroy", :as => "log_out"
get "log_in" => "sessions#new", :as => "log_in"
resources :sessions

The resources :sessions line defines the full set of RESTful routes for SessionsController, but because of the first two lines, you don't need them.

Am I correct?

Avatar

Thanks, rehashing is what I needed, too

Avatar

Found this line, from here:

ruby
page.execute_script %Q{ $('.ui-menu-item a:contains("#{the_option_text_you_want_to_choose}")').trigger("mouseenter").trigger("click"); }

And it works!

Avatar

Does anybody know how to include the author's name in the facet results. I'm trying to figure out if I can avoid looking up the Author for each facet:

ruby
Author.find(facet['term']).name

I was trying to see if I could get the facet to return more than one value like this:

ruby
facet "authors" do
  terms [:author_id, :name]
end
Avatar

How would one test this with rspec & capybara? I haven't been able to select an option from the autocomplete list with capybara. Anyone been successful with this?

Avatar

I spent a bunch of time researching providers because of the common theme in licensing terms, even with Geocoder.ca.

For the giants (Google, Yahoo, Bing) you are prohibited from doing anything for free other than displaying on their mapping API, including caching the results. Geocoder.ca requires you to be non-profit and provide attribution.

I eventually settled on GIS @ USC -- their terms are much less restrictive, I don't mind giving them attribution, and past the free 2500 transactions they're incredibly cheap in comparison to other commercial licenses (10k transactions = $20, 1M transactions = $1600.)

Handling the web service was a minimal amount of code using Net::HTTP::Post for transport, Nokogiri parses the XML, and I can cache results without worry. Maybe not the solution for everyone, but pretty well what I was looking for! Hope this helps someone...

Avatar

I'm pretty new to rails and mercury and I have some troubles to save.

I've implemented the editor on one controller and I want to send the save request to the same controller. I want to update so i use the "PUT" method right.

But the lo tells me that there is no route to url.

Controller:
  def update
  .
  .
  .
  end


  include Mercury::Authentication

  layout :layout_with_mercury
  helper_method :is_editing?

  private

  def layout_with_mercury
    !params[:mercury_frame] && is_editing? ? 'mercury' : 'application'
  end

  def is_editing?
    cookies[:editing] == 'true' && can_edit?
  end
mercury.html.erb
    <script type="text/javascript">
      // Set to the url that you want to save any given page to, leave null for default handling.
      var saveUrl = null

      // Instantiate the PageEditor
      new Mercury.PageEditor(saveUrl, {
        saveStyle: 'form', // 'form', or 'json' (default json)
        saveMethod: 'PUT', // 'PUT', or 'POST', (create, vs. update -- default PUT)
        visible:    true  // boolean - if the interface should start visible or not
      });
    </script>
routes.rb
Pitchdot::Application.routes.draw do
  
 
  mount Mercury::Engine => '/'

 resources :users
 resources :sessions, only: [:new, :create, :destroy]
 resources :pitchdecks 
 
  get "static_pages/privacy"

  root to: 'static_pages#home'
  
  match '/signup',  to: 'users#new'
  match '/signin',  to: 'sessions#new'
  match '/signout', to: 'sessions#destroy', via: :delete
 
  match '/help',    to: 'static_pages#help'
  match '/about',   to: 'static_pages#about'
  match '/jobs',    to: 'static_pages#jobs'
  match '/terms',   to: 'static_pages#terms'
  match '/privacy', to: 'static_pages#privacy'

end

Maybe you can help me. Thanks!

Avatar

Ryan, I guess you are missing rbenv global 1.9.2-p290 in instructions. Thanks for this awesome screencast!

Avatar

In addition to that, I also have major problems with the Callbacks. If I use it, the in-place-edit function simply stops working.

Avatar

Hi, I am having a problem when trying two different providers, Linkedin and Facebook. Hope you can help me.

For example once I logged using facebook, and logout from the site, then try to login using linkedin I got an error.

Here's my code.

Gemfile
gem 'devise'
gem 'omniauth-facebook'
gem 'omniauth-linkedin'
config/initializers/devise.rb
config.omniauth :facebook, "CONSUMER_KEY","CONSUMER_SECRET"
config.omniauth :linkedin, "CONSUMER_KEY", "CONSUMER_SECRET" "
controllers/omniauth_callbacks_controller.rb
class OmniauthCallbacksController < Devise::OmniauthCallbacksController

        def facebook
              user = User.from_omniauth(request.env["omniauth.auth"])
            if user.persisted?
                    
              sign_in_and_redirect user
            else
              session["devise.user_attributes"] = user.attributes
              redirect_to new_user_registration_url
            end
          end

          def linkedin
            user = User.from_omniauth(request.env["omniauth.auth"])
            if user.persisted?
                    
              sign_in_and_redirect user
            else
              session["devise.user_attributes"] = user.attributes
              redirect_to new_user_registration_url
            end
          end


           alias_method :facebook, :linkedin
end
models/user.rb
class User < ActiveRecord::Base
  
  devise :database_authenticatable, :registerable, :validatable,
         :recoverable, :rememberable, :trackable,  :omniauthable

  # Setup accessible (or protected) attributes for your model
  attr_accessible :email, :password, :password_confirmation, :remember_me, :username,
   :provider, :uid, :name, :oauth_token, :oauth_expires_at, :fname, :lname, :user_type, :username

 
 
   validates_presence_of :fname
   validates_presence_of :lname

    has_attached_file :photo,
        :default_url => '/assets/default1.gif'

        has_many :experiences

         def self.from_omniauth(auth)
          where(auth.slice(:provider, :uid)).first_or_create do |user|
            user.provider = auth.provider
            user.uid = auth.uid
                   user.email2 = auth.info.email
            user.fname = auth.info.first_name
            user.lname = auth.info.last_name
          end
        end


        def self.new_with_session(params, session)
                  if session["devise.user_attributes"]
                    new(session["devise.user_attributes"], without_protection: true) do |user|
                      user.attributes = params
                      user.valid?
                    end
                  else
                    super
                  end    
        end


        def password_required?
                  super && provider.blank?
        end

        def email_required?
                  super && provider.blank?
        end

end
My Error
ActiveRecord::RecordNotUnique in OmniauthCallbacksController#linkedin

PG::Error: ERROR:  duplicate key value violates unique constraint "index_users_on_email" 
Avatar

How can you fix n + 1 queries on a has :through association?

Avatar

Wow, who knew! I can't picture how this could work, but seems interesting!

Avatar

I'm getting a Missing partial in the link_to_add_fields method and can't for the life of me figure out why. I've followed the setup exactly as described in the RailsCast.

It seems to be coming from this line:

ruby
render(association.to_s.singularize + "_fields", :f => builder)
Avatar

@diasks2 - Thank you so much for this. You just saved me a few hours!

Avatar

FYI, If you're trying this in your own app and not seeing the etag headers, it could be because MiniProfiler (described in episode #368) strips the etag headers and rewrites the cache-control header. See my comment in that episode: http://railscasts.com/episodes/368-miniprofiler?view=comments#comment_159804

Avatar

I was trying the caching techniques from episode #321 and pulling my hair out trying to figure out why I wasn't get etag headers in my responses. Turns out that MiniProfiler strips the etag headers. It also rewrites the Cache-Control header.

From MiniProfiler source: mini-profiler/profiler.rb

ruby
# mini profiler is meddling with stuff, we can not cache cause we will get incorrect data
# Rack::ETag has already inserted some nonesense in the chain
headers.delete('ETag')
headers.delete('Date')
headers['Cache-Control'] = 'must-revalidate, private, max-age=0'
[status, headers, body]

Probably isn't a big deal because the profiler is disabled in production. But makes things trickier on the development side. Just wanted to share this in case anyone hits the same issue.

Avatar

I ended up using the static version of twitter bootstrap.

according to docs on the github, just include

gem 'twitter-bootstrap-rails', :git => 'git://github.com/seyhunak/twitter-bootstrap-rails.git', :branch => 'static'

in your gem file.

Avatar

Is it possible to Create Ransack::Search object without querying DB ?

I'd like to be able to create a Ransack::Search object to be passed into a search_form_for, but the initial creation of the search object queries the database, wich I don't want.

I want to show an initial blank form with Ransack::Search options to search, without calling the database.

How can I do that ?

Asked in stackoverflow

Avatar

even better,

<% publish_to "/messages/new" do %>
$("#chat").append("<%= escape_javascript render(@message) %>");
$("#chat").animate({ scrollTop: $("#chat").height() }, "fast");
<% end %>

This second line makes sure that the scroll is animated to the bottom so that it shows the newly appended message!

Avatar

There is a slight mistake in the screencast. It should be xc:red instead of cx:red when canvas:red is not working.

Avatar

Great episode as always...

i implement this episode to my event model. Some events have a duration of more than 1 day...by example event "A" is 3 day's. Has anybody implement this feature yet. So with 2 columns in the DB 'starts_at' and 'ends_at' and the calendar is filled in between this data?

Ciao..remco

Avatar

def find_commentable
params.each do |name, value|
if name =~ /(.+)_id$/
return $1.classify.constantize.find(value)
end
end
nil
end

Always raises the exception, it seems it doesn't get the commentable_id parameter, so what can i do to make this work.

Avatar

Just switched from MySQL to PostgreSQL and now seeing 0 SQL queries. I'm on 0.14.0 of the pg gem and do not have mysql in my Gemfile. Project is open source.

UPDATE: Problem was that pg was being loaded after miniprofiler. I fixed this by moving the pg gem to the top level of my Gemfile (i.e. outside any groups).

Avatar

I have been messing around with this today but for some reason I still can't figure out where the following functions are defined and my rails server keeps telling me they are undefined:
Products.page(page).per_page(per_page) and products.total_entries.

Any help would be great.

Avatar

ok. So I just edited /etc/nginx/sites-enabled/default and changed the root element in server {} to

root /usr/share/nginx/html

rather than

root /usr/share/nginx/www

and it works. Moving on. Once I get the kids. :)

Avatar

I also. I'll look further tonight, but have either of you resolved this? Here is the error in the nginx/error.log:

rewrite or internal redirection cycle while internally redirecting to "/index.html"

so it's something in the default config settings.

Avatar

Any recommendations for generating an .ics file for the date selected? The ri_cal library on github appears to be getting no love. And from the examples, I am not quite sure where to put the code (this video suggests creating a helper).

Any assistance is very appreciated.

Avatar

Typo in the /app/controllers/comments_controller.rb code block in 'Read the episode'

@commentable = resource.singularize.classify.contantize.find(1)

... missing the 's' in constantize