开发者

Overriding primary key protection in Rails

开发者 https://www.devze.com 2022-12-13 12:55 出处:网络
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.

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.

0

精彩评论

暂无评论...
验证码 换一张
取 消