如何在控制器#create中按类型和名称属性查找对象?

时间:2011-12-01 12:48:38

标签: ruby-on-rails-3.1 findby

实际上我正在测试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

模型/ transaction.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)

我做错了什么?

1 个答案:

答案 0 :(得分: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]])

我希望这会有所帮助。