views:

59

answers:

3

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 the 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

A: 

Use attribute direct assignment. You can also take advantage of blocks.

Model.create! do |m|
  m.id = 27
  m.attribute = "foo"
end
Simone Carletti
Not ideal for seed data where you're trying to create significant numbers of records.
Rare Pleasures
I'm using FactoryGirl plugin both for seeds and tests. It uses the aforementioned technique to bypass any mass_assignment restriction.
Simone Carletti
A: 

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
Steve Graham
But when you need to, you need to.
Rare Pleasures
A: 

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.

hakunin
'Removing mass-assignment protection for the sake of seeding is, let's just say, unwise.'- Yes but when you want to do it it should be agnostic enough to let you do it.I overlooked iterating over the hash. Apols.
Rare Pleasures