0

I have a rake task to create a number of invoices in my Rails application:

def make_invoices
  Project.all.each do |project|
    i = project.invoices.create!( :number     => random_number,
                                  :date       => random_date,
                                  :recipient  => random_recipient,
                                  :user_id    => project.person.user.id)        
    i.created_at = random_time
    i.save
  end
end

This line causes the rake task to fail, however:

:user_id => project.person.user.id

And I get the following error:

Can't mass-assign protected attributes: user_id

I know why this happens.

But I need to run this rake task and I wonder if there's any way to force mass-assign or something?

Each invoice's project_id is set automatically by the invoices.create! method. But what if I need to set a user_id as well?

Thanks for any help.

Tintin81
  • 9,821
  • 20
  • 85
  • 178

2 Answers2

1

You need to do it outside of the call to create and change it to build:

def make_invoices
  Project.all.each do |project|
    i = project.invoices.build( :number     => random_number,
                                  :date       => random_date,
                                  :recipient  => random_recipient)   

    i.user_id = project.person.user.id
    i.save!

    i.created_at = random_time
    i.save
  end
end
Shane Andrade
  • 2,655
  • 17
  • 20
  • That works, thanks! Why is `build` better than `create` in this context? Do I really need to call `save` twice here? – Tintin81 Jan 30 '13 at 18:15
  • Create will initialize and save the model to the database, where build just initializes it. No, you don't need save twice, I just put it there to keep the same behavior as your original code, but you can get rid of the first one. – Shane Andrade Jan 30 '13 at 18:19
1

(Possible duplicate of "Is there a way to bypass mass assignment protection?")

It seems that assign_attributes can do that:

user = User.new
user.assign_attributes({ :name => 'Josh', :is_admin => true }, :without_protection => true)
user.name       # => "Josh"
user.is_admin?  # => true
Community
  • 1
  • 1
MrYoshiji
  • 54,334
  • 13
  • 124
  • 117