我有模型Student
和控制器StudentsController
。
我在控制器中有这个代码:
def create_students_list
@students=[...#some code which evaluates to array of student instances]
result=list_transaction(@students)
...
end
private
def list_transaction(collection, options= {})
errors=[]
ActiveRecord::Base.transaction do
collection.each do |item|
if item.save
else
errors << item.errors
end
end
end
if errors.any?
{:success=>false, :errors => errors }
else
{:success => true}
end
end
这个想法是:我有大量的输入,我想在交易中包装。还有一些其他逻辑,而不是这里的问题。 但我想要DRY控制器,我也需要其他控制器的相同操作,所以我决定使用PORO方法:拥有可以重用的纯Ruby对象。
class List
include ActiveRecord
include ActiveRecord::Transactions::ClassMethods
def initialize(collection)
@collection=collection
end
def group_input
outputs={:valid=>[], :invalid=>[]}
@collection.each do |element|
if element.valid?
outputs[:valid] << element
else
outputs[:invalid] << [element, element.errors]
end
end
if outputs[:valid].any?
save_list(outputs[:valid])
outputs[:something_saved]=true
outputs[:valid].delete
end
save_list(outputs[:valid])
if outputs[:invalid].empty?
outputs = {}
outputs[:all_records_saved]=true
else
outputs=outputs[:invalid]
end
outputs
end
private
def save_list(collection)
ActiveRecord::Base transaction do
collection.each do |element|
element.save
end
end
end
end
问题:它会导致错误:
NameError:
undefined local variable or method `connection' for #<List:0x000001073a62d8 @collection=[#<Student id: nil>]>
尝试使用ActiveRecord :: ConnectionsHandler,这也引发了:
NameError:
undefined local variable or method `connection_handler' for #<List:0x0000010c285480 @collection=[#<Student id: nil>]>
我不知道如何使这个工作
答案 0 :(得分:1)
您似乎还需要包含其他ActiveModel
类
class List
include ActiveRecord::Base.transaction
extend ActiveModel::Naming
include ActiveModel::Conversion
include ActiveModel::Validations
#... rest of the code
end