new
- 1.0.0 (0)
- 1.1.6 (0)
- 1.2.6 (0)
- 2.0.3 (0)
- 2.1.0 (0)
- 2.2.1 (0)
- 2.3.8 (0)
- 3.0.0 (0)
- 3.0.9 (0)
- 3.1.0 (23)
- 3.2.1 (0)
- 3.2.8 (0)
- 3.2.13 (0)
- 4.0.2
- 4.1.8
- 4.2.1
- 4.2.7
- 4.2.9
- 5.0.0.1
- 5.1.7
- 5.2.3
- 6.0.0
- 6.1.3.1
- 6.1.7.7
- 7.0.0
- 7.1.3.2
- 7.1.3.4
- What's this?
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.
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?
4.0.2 support
Where did this go in 4.0.2?