Overriding primary key protection in Rails
Is there a way to overide the mass assignment protection on a model's primary key in Rails ? My seed.rb data won't load because of it.
Update
I've found including t开发者_如何学Che following code in the model removes the protection
def attributes_protected_by_default
default = super
default.delete self.class.primary_key
default
end
Not ideal
Use attribute direct assignment. You can also take advantage of blocks.
Model.create! do |m|
m.id = 27
m.attribute = "foo"
end
I'm using rails 3.1 and none of the above answers work for me (working with a legacy db schema).
This works though:
class ActiveRecord::Base
def self.no_pk_protection!
# yikes
default_scope :order => primary_key # this is necessary so first and last don't fail
attr_accessor :mock_pk
set_primary_key :mock_pk
end
end
...and then:
class Category < ActiveRecord::Base
no_pk_protection!
end
There is rarely a need to directly touch foreign keys e.g.
post = Post.create :title => "Lorem ipsum", :text => "dolor sit amet…"
comment = Comment.create :text => "Etiam mi mi, imperdiet a tempus suscipit…"
comment.post = post
Removing mass-assignment protection for the sake of seeding is, let's just say, unwise. Weppos suggested using direct assignment, to which you said:
Not ideal for seed data where you're trying to create significant numbers of records.
How does using direct assignment make a difference? You can iterate over an array or hash of data populating it with direct assignment just as easily as passing hash into constructor. You aren't really saving anything.
Another way would be to populate database directly with raw SQL, but seeding is not the kind of operation you need to run so frequently that it must be optimized.
精彩评论