How to get better error messages for an associated model.
Hey there. Let's assume you have some set like this
class User < ActiveRecord::Base
  has_one :profile , :dependent => :destroy
end


class Profile < ActiveRecord::Base
  belongs_to :user
  validates_presence_of :first_name, :last_name
end

And you create the profile in the same view as your user. How do you validate those first_name and last_name fields with a friendly message for your user?
Well, you could use validates_associated, but you would end up with a message like "Profile is invalid". Now, how friendly is that?

To obtain a more precise message, use this on you user.rb

def validate
  if self.profile
    self.profile.errors.each do |error|
      self.errors.add_to_base error.join(' ')
    end
  end
end
Diff entre respond_to? e respond_to

Um pequeno tutorial em português pra diferenciar melhor respond_to? e respond_to. Não parece ter muita não? Mas o tio Chuck Norris vai me ajudar a esclarecer melhor isso aqui.

respond_to? é um método do Ruby Core como você pode ver, e não do Ruby On Rails, ele basicamente verifica se determinado objeto responde a um método, como o nome sugere mesmo.

Por exemplo:

class Chuck < Object
  def norris
    puts "the man"
  end
end
chuck_norris = Chuck.new
p chuck_norris.respond_to?("norris") # true
p chuck_norris.respond_to?("mr_t") # false

Já o respond_to, sem o ponto de interrogação (eles fazem parte do nome do método) faz parte do ActionController do Ruby On Rails. Ele coloca suporte a Web Service na sua aplicação, isso quer dizer que ele consegue resolver o tipo do recurso que você deseja.

respond_to do |format|
  format.html # render por default nome_da_acao.html.erb
  format.js # render o nome_da_acao.rjs
  format.xml { render :xml => @chuck.to_xml } # coloca o chuck pra xml e envia
end

Com esse código na action você poderia usar, por exemplo:

http://localhost:3000/nome_da_acao.html
http://localhost:3000/nome_da_acao.xml

Ou realizar uma chamada JS unobstrusive usando AJAX.

Isso ai, espero ter ajudado.

Installing RMagick on Ubuntu

Last week I was installing again rmagick on a Ubuntu server, then I discovered an very easy way to do it.

$ sudo aptitude install librmagick-ruby

Edit 10/20/08: Avoid this tutorial it doesn't work, if you wanna install rmagick use the old fashion way:

$ sudo apt-get install imagemagick
$ sudo apt-get install libmagick9-dev
$ sudo gem install rmagick