method

new

Importance_3
v1.1.6 - Show latest stable - 3 notes - Class: ActiveRecord::Base
new(attributes = nil) public

New objects can be instantiated as either empty (pass no construction parameter) or pre-set with attributes but not yet saved (pass a hash with key names matching the associated table column names). In both instances, valid attribute keys are determined by the column names of the associated table — hence you can’t have attributes that aren’t part of the table columns.

Show source
Register or log in to add new notes.
April 16, 2009
3 thanks

Various use cases

Example

user = User.new
user.name = 'Akhil Bansal'
user.save

user =  User.new(:name => 'Akhil')
user.save

User.new do |u|
  u.name = 'Akhil'
  u.save
end
March 24, 2010
1 thank

Setting primary key from hash

If you try to specify the value for your primary key (usually “id”) through the attributes hash, it will be stripped out:

Post.new(:id => 5, :title => 'Foo') #=> #<Post @id=nil @title="Foo">

You can solve this by setting it directly, perhaps by using a block:

Post.new(:title => "Foo") { |p| p.id = 5 } #=> #<Post @id=5 @title="Foo">

This behavior is something you’d probably only have a problem with when you have custom primary keys. Perhaps you have a User model with a primary key of “name”…

class User < ActiveRecord::Base
  set_primary_key :name
end

User.new(params[:user]) # This will never work

You can solve this on a case-to-case basis by calling attributes= directly with the “ignore protected” option:

User.new { |user| user.send(:attributes=, params[:user], false) } # BAD BAD BAD!

You should not do the above example, though. If you do, all protected attributes are ignored, which is very, very bad when you only care about the primary key.

I’d recommend one of the following instead:

# Option 1 – Always allow primary key. Avoid with models created by users
class User
  private
    def attributes_protected_by_default
      super - [self.class.primary_key.to_s]
    end
end

# Option 2 – Add a new method for this case
class User
  def self.new_with_name(attributes = nil)
    new(attributes) { |u| u.name = attributes[:name] }
  end
end

As always when something is hard to do in Rails: Think about your design? Is it recommended? Is it sound? Do you really need to have a custom primary key?

July 30, 2014 - (>= v4.0.2)
0 thanks

4.0.2 support

Where did this go in 4.0.2?