ActiveRecord create without_protection - wrong num

2020-07-18 02:29发布

问题:

I can't work out what's wrong with this create statement on my User model:

User.create({first_name: "Alan",....}, :without_protection => true)

Gives me the stack trace:

ArgumentError: wrong number of arguments (2 for 1)
from /Users/alanheppenstall/.rvm/gems/ruby-1.9.3-p362/gems/activerecord-4.0.0/lib/active_record/persistence.rb:32:in `create'
from (irb):56
from /Users/alanheppenstall/.rvm/gems/ruby-1.9.3-p362/gems/railties-4.0.0/lib/rails/commands/console.rb:90:in `start'
from /Users/alanheppenstall/.rvm/gems/ruby-1.9.3-p362/gems/railties-4.0.0/lib/rails/commands/console.rb:9:in `start'
from /Users/alanheppenstall/.rvm/gems/ruby-1.9.3-p362/gems/railties-4.0.0/lib/rails/commands.rb:64:in `<top (required)>'
from bin/rails:4:in `require'
from bin/rails:4:in `<main>'

My syntax matches: http://apidock.com/rails/ActiveRecord/Base/create/class/

I'm using devise with this model - could that be an issue? I couldn't find anywhere where they override initialize().

Thanks!

回答1:

OK, they removed options in Rails 4 and this hasn't been updated in places like APIdock (http://apidock.com/rails/ActiveRecord/Base/create/class/)

You can see the difference between current and 3.2:

https://github.com/rails/rails/blob/master/activerecord/lib/active_record/persistence.rb

and

https://github.com/rails/rails/blob/3-2-stable/activerecord/lib/active_record/persistence.rb



回答2:

It's removed in rails 4

Now you can just create without setting the flag

User.create({id: 101, first_name: "Alan",....})

Rails will create new record with id = 101 without the flag

But you will get an error if any record with id 101 already exist

ActiveRecord::RecordNotUnique: PG::UniqueViolation: ERROR: duplicate key value violates unique constraint "users_pkey"