在变量中存储关联

时间:2014-04-13 13:05:13

标签: ruby-on-rails

嘿我正在尝试使方法具有多态性,以便它可以访问不同的模型关联,但对它们进行相同的处理

module Unitable

    # Adds new units without duplication
    def add_units(type, units = {}) 
        if type.downcase == "army"
            relationships = self.members
        elsif type.downcase == "character"
            relationships = self.owns
        end

        units.each do |name, amount| 
            unit = Unit.find_by(name: name)
            if relationships.where(unit_id: unit.id).first.nil?
                relationships.create(unit_id: unit.id, amount: amount) #<--- This is where the error occurs
            else
                relationship = relationships.find_by(unit_id: unit.id) 
                original_amount = relationship.amount
                new_amount = amount + original_amount
                relationship.update_attribute(:amount, new_amount)
            end
        end
    end

end

抛出

ERROR:  current transaction is aborted, commands ignored until end of transaction block

这是根方法

def gen_starting_units
    credit = 9
    #transaction do
        units = Unit.tagged_with(["#{race}", "1"]).sample(2)
        while credit > 0
            unit = units.sample
            if unit.cost <= credit
                self.army.add_units("army", unit.name => 1)
                credit -= unit.cost
            end                         
        end         
    #end
end

0 个答案:

没有答案