模型中belongs_to条件的问题

时间:2013-06-01 17:17:53

标签: ruby-on-rails ruby-on-rails-3 postgresql pg

我正在制作个人理财应用程序。我有2个模型:AccountTransactionTransactionbelongs_to :accountAccounthas_many :transactions

当我在db(postgres)中有account_id列时,一切正常。但我必须将account_id重命名为from_account_id并添加另一列to_account_id。这样我就可以将Account和收入增加到Account。此外,帐户之间的转帐也是必要的(其中from_account_idto_account_id都有一些值。)

因此,我已将观看中的字段:account_id重命名为:from_account_id并添加:to_account_id字段。但是,当我在db中将account_id重命名为from_account_id时,我遇到了这个错误。

ActiveRecord::StatementInvalid in PagesController#index

PG::Error: ERROR:  column transactions.account_id does not exist
LINE 1: ...s".* FROM "transactions" INNER JOIN "accounts" ON "transacti...
                                                             ^
: SELECT "transactions".* FROM "transactions" INNER JOIN "accounts" ON
  "transactions"."account_id" = "accounts"."id" WHERE "accounts"."user_id" = 17 ORDER BY
  transactions.date DESC

我的Pages#index控制器是:

class PagesController < ApplicationController

  def index
    if user_signed_in?
      @accounts = current_user.accounts.all
      @transaction = current_user.transactions.build
      @transactions = current_user.transactions.all
      @categories = current_user.categories.all
    end
  end

end

我认为Rails正试图在account_id表中找到transactions列,因为Transaction belongs_to :account。但正如您所见,我需要:account tofrom两个列。所以,也许我需要在belongs_to模型中更改此Transaction条件,但我不知道如何。

感谢您的任何想法!

2 个答案:

答案 0 :(得分:1)

哟必须重命名has_many模型中的Account关系。像下面这样的东西会起作用:

has_many :transactions, :foreign_key => "from_account_id"

答案 1 :(得分:1)

您必须在belong_to课程中定义两个Transaction关系,表格transactions中每列一个:

class Transaction < ActiveRecord::Base    
  belongs_to :from_account, :class_name => 'Account', :foreign_key => 'from_account_id'
  belongs_to :to_account, :class_name => 'Account', :foreign_key => 'to_account_id'

  # ...
end

请参阅Rails Relation Guide

中的选项