new
new(attributes = nil, options = {})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.
initialize respects mass-assignment security and accepts either :as or :without_protection options in the options parameter.
Examples
# Instantiates a single new object User.new(:first_name => 'Jamie') # Instantiates a single new object using the :admin mass-assignment security role User.new({ :first_name => 'Jamie', :is_admin => true }, :as => :admin) # Instantiates a single new object bypassing mass-assignment security User.new({ :first_name => 'Jamie', :is_admin => true }, :without_protection => true)
2Notes
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
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?