Tag Archives: Ruby

rails generate Could not find <gem> in any of the sources

So with my latest project I am using Rails 4.1 – this is all well and good, but here is a gotcha. there is a thing called spring that is supposed to make things faster – except when it gets in the way!

tl;dr – killall spring

So – here are the symptoms

$ rails g
Could not find bcrypt-3.1.7 in any of the sources
Run `bundle install` to install missing gems.

Now bcrypt is the only thing having the issue (other gems worked) i think this is because it has a compiled binary component to it.

The fix? Kill all the springs!

$ ps aux | grep spring
jason     8361  0.0  0.2 426464 21380 ?        Sl   Apr22   0:01 spring server | wholesale | started 22 hours ago                                                                
jason    11730  1.0  0.2 225632 22276 ?        Ssl  11:46   0:00 spring app    | wholesale | started 55 secs ago | development mode

$ kill 8361

… and now rails generate plays nicely again!

Rails, CanCan and Best In Place editing

So here is a little gotcha and solution when using CanCan and Best In Place. With the default setup, if CanCan auth fails on a best in place edit you get a redirect to your default “Auth Failed” path and that page then tries to render as javascript.

that does not work all that well!

So here is my simple solution, if we get an auth denied on a XHR request, just return a generic error!

class ApplicationController < ActionController::Base

	rescue_from CanCan::AccessDenied do |exception|
		if request.xhr?
			render :json => ['You are not authorised to do that.'], :status => :unprocessable_entity
			redirect_to '/', :alert => exception.message

has_many :through and the case of the missing include

tl;dr – you need to specify the “inverse_of” option on your has_many/belongs_to relationship to get your children fully populated

So I came across an interesting situation the other day, where my includes() statement was preloading data, but then when accessing it I would see another SQL query.

require 'active_record'

class Parent < ActiveRecord::Base
attr_accessible :name
has_many :parent_children, inverse_of: :children
has_many :children, through: :parent_children

default_scope includes(:parent_children)

class ParentChildren < ActiveRecord::Base
attr_accessible :parent_id, :child_id
belongs_to :parents, inverse_of: :parent_children
belongs_to :children

default_scope includes(:children)

class Child < ActiveRecord::Base
attr_accessible :name
has_many :parent_children
has_many :parents, through: :parent_children

Parent.all.each {|p| p.children.each {|c| puts c.name}}

Without the :inverse_of here, each call to write the childs name will result in a new SQL query to get the data, even though this data has already been prefetched (eager loaded).