[英]How to set two foreign keys with a Rake Task in Ruby on Rails?
I have a rake task to create a number of invoices
in my Rails application: 我有一个rake任务在我的Rails应用程序中创建一些
invoices
:
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: 但是,此行导致rake任务失败:
: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? 但是我需要运行这个rake任务,我想知道是否有任何方法强制进行质量分配或其他什么?
Each invoice's project_id
is set automatically by the invoices.create!
每张发票的
project_id
都是由invoices.create!
自动设置的invoices.create!
method. 方法。 But what if I need to set a
user_id
as well? 但是,如果我还需要设置
user_id
呢?
Thanks for any help. 谢谢你的帮助。
You need to do it outside of the call to create
and change it to build
: 您需要在调用之外执行此操作以
create
并更改它以进行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
(Possible duplicate of "Is there a way to bypass mass assignment protection?" ) (可能重复“有没有办法绕过质量分配保护?” )
It seems that assign_attributes can do that: 似乎assign_attributes可以做到这一点:
user = User.new
user.assign_attributes({ :name => 'Josh', :is_admin => true }, :without_protection => true)
user.name # => "Josh"
user.is_admin? # => true
声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.