0

实际上,我正在测试plutus gem的复式记账。我有账户和交易。当你想记录交易时,有以下步骤:

1-创建将接收交易金额的 2 个帐户(例如现金(借方)和提款(贷方)。

2-您创建一个交易并将他的金额传递给您在步骤 1 中创建的 debit_account 和 credit_account。您通过查找帐户类型来完成它,然后是它的名称(参见 transactions_controller.rb)

模型/account.rb

class Account < ActiveRecord::Base

    set_inheritance_column do
        "type" + "_id"
    end

    validates_presence_of :name, :type
    validates_presence_of :name

    has_many :credit_transactions,  :class_name => "Transaction", :foreign_key => "credit_account_id"
    has_many :debit_transactions,  :class_name => "Transaction", :foreign_key => "debit_account_id"
      has_many :transactions
      accepts_nested_attributes_for :transactions 
end

模型/事务.rb

class Transaction < ActiveRecord::Base
  belongs_to :commercial_document, :polymorphic => true
  belongs_to :credit_account, :class_name => "Account"
  belongs_to :debit_account, :class_name => "Account"
  belongs_to :account


  validates_presence_of :credit_account, :debit_account, :amount, :description
  validates_associated :credit_account, :debit_account
end

控制器/transactions_controller.rb

  def new 

      @transaction = Transaction.new

      respond_to do |format|
          format.html #new.html.erb
          format.json { render :json => @transaction }
        end
    end 

        def create
        @transaction = Transaction.new(params[:transaction])
        @transaction.credit_account = Account.where(:type => params[:type]).where(:name => params[:name]) 
        @transaction.debit_account =  Account.where(:type => params[:type]).where(:name => params[:name])

        respond_to do |format|
          if @transaction.save
            format.html { redirect_to @transaction, :notice => 'Transaction was successfully created.' }
            format.json { render :json => @transaction, :status => :created, :location => @transaction }
          else
            format.html { render :action => "new" }
            format.json { render :json => @transaction.errors, :status => :unprocessable_entity }
          end
        end
      end

交易/_form.html.erb

<%= simple_form_for @transaction do |f| %>

  <%= f.input :description %>
  <%= f.input :debit_account %>
  <%= f.input :credit_account %>
  <%= f.input :amount %>

  <%= f.button :submit %>   

<% end %>

当我提交交易时,我收到以下错误消息

ActiveRecord::AssociationTypeMismatch in TransactionsController#create
Account(#2160906760) expected, got String(#2151988680)

我究竟做错了什么?

4

1 回答 1

1

请替换以下代码:

@transaction.credit_account = Account.where(:type => params[:type]).where(:name => params[:name]) 
@transaction.debit_account =  Account.where(:type => params[:type]).where(:name => params[:name])

@transaction.credit_account = Account.find(:all, :conditions => [:type => params[:type], :name => params[:name]])  
@transaction.debit_account =  Account.find(:all, :conditions => [:type => params[:type], :name => params[:name]])

我希望这有帮助。

于 2011-12-08T13:21:22.387 回答