Warning: file_get_contents(/data/phpspider/zhask/data//catemap/0/windows/17.json): failed to open stream: No such file or directory in /data/phpspider/zhask/libs/function.php on line 167

Warning: Invalid argument supplied for foreach() in /data/phpspider/zhask/libs/tag.function.php on line 1116

Notice: Undefined index: in /data/phpspider/zhask/libs/function.php on line 180

Warning: array_chunk() expects parameter 1 to be array, null given in /data/phpspider/zhask/libs/function.php on line 181
Ruby on rails 如何将多个RubyonRails数据库查询封装到一个原子语句中?_Ruby On Rails - Fatal编程技术网

Ruby on rails 如何将多个RubyonRails数据库查询封装到一个原子语句中?

Ruby on rails 如何将多个RubyonRails数据库查询封装到一个原子语句中?,ruby-on-rails,Ruby On Rails,我正在处理多个RubyonRails数据库查询,其中包括两个不同的数据库。我希望将它们封装起来,以便在其中一个查询失败时,所有其他查询都必须回滚。简而言之,我想把它们转换成一个原子语句 # a) LocationRole.create!( role: new_params[:role], resource_type: 'Hub', resource_id: hub_data[:hub_id], user_id: new_params[:user_id] ) # b) Locat

我正在处理多个RubyonRails数据库查询,其中包括两个不同的数据库。我希望将它们封装起来,以便在其中一个查询失败时,所有其他查询都必须回滚。简而言之,我想把它们转换成一个原子语句

# a)
LocationRole.create!(
  role: new_params[:role],
  resource_type: 'Hub',
  resource_id: hub_data[:hub_id],
  user_id: new_params[:user_id]
)

# b)
LocationRole.create!(
  role: new_params[:role],
  resource_type: 'Cluster',
  resource_id: input[:cluster_id],
  user_id: new_params[:user_id]
)

# c)
User.create(:email=>email,:password=>password,:user_type=>user_type)

将它们包装到事务中:

ActiveRecord::Base.transaction do
#(a)
#(b)
#(c)
终止
您可能需要调用
User.create(使用bang)而不是
用户。创建
,以便在出现验证错误时引发异常。每当在事务内引发异常时,该事务将回滚