views:

51

answers:

1

Suppose a simple ActiveRecord model corresponding to a table with just two columns, id and name:

class Model < ActiveRecord::Base
  def self.my_create(name)
    create(:name => name)
  end
end

If I call Model.my_create, a record is created and saved:

>> Model.my_create('foo')
=> #<Model id: 1, name: "foo">

But If I call Model.create straight, the record is not saved:

>> Model.create(:name => 'bar')
=> #<Model id: nil, name: "bar">

How come calling create in a class method has different behaviour than calling it straight as a class method?

+3  A: 

Model.create(...) works fine for me.

It's probably worth using Model.create! which will raise an exception if there's a validation error which is probably the cause of the record not being saved or you could check the errors on the returned instance. I've been bitten by Model.create before because it leaves it up to you to check whether the object was saved or not and for what reason.

Shadwell