venerdì 28 gennaio 2011

Rails 3 scopes with HABTM (has and belongs to many) relations

There are already many posts about this, but maybe this simple example will help you understand this subject even better.

# First model: tag.rb
# note that pomodori is a custom plural for pomodoro
class Tag < ActiveRecord::Base
has_and_belongs_to_many :pomodori
end
# Second model: pomodoro.rb
# here is how to define a Rails 3 scope through the join table:
class Pomodoro < ActiveRecord::Base
has_and_belongs_to_many :tags
scope :by_tag, lambda { |tag_text|
joins("join pomodori_tags, tags").
where('pomodori.id = pomodori_tags.pomodoro_id
AND pomodori_tags.tag_id = tags.id
AND tags.text = ?', tag_text)
}
end
view raw habtm_scope.rb hosted with ❤ by GitHub

martedì 18 gennaio 2011

invalid option: --with-pg-dir=/opt/PostgreSQL/9.0

I'd bet a lot of ruby devs actually found themselves stuck in this problem. You checkout a github repo, you run a bundle install and = duh = a gem cannot install because of a missing library.
You're sure you've already installed the library or dependency or whatever, but in a different path from the standard one (in this example I'm talking about PostgreSQL installed via the graphical installer instead of the ubuntu apt repo); so you issue the command

gem install pg -v0.9.0 --with-pg-dir=/opt/PostgreSQL/9.0

And you get this error message: invalid option: --with-pg-dir=/opt/PostgreSQL/9.0

What's the problem? You need to separate options with another pair of dashes:

gem install pg -v0.9.0 -- --with-pg-dir=/opt/PostgreSQL/9.0

And everything will work.