0

I'm making personal money management app. There I have 2 models: Account and Transaction. Transaction has belongs_to :account and Account has has_many :transactions.

When I had account_id column in db (postgres) everything worked fine. But I have to rename account_id to from_account_id and add another column to_account_id. So that I can add a spending from Account and income to Account. Also it's necessary for transfers between accounts (where from_account_id and to_account_id both will have some values).

So, I've renamed fields :account_id in my views to :from_account_id and add :to_account_id field. But, when I rename account_id to from_account_id in db, I've got this error.

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

My Pages#index controller is:

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

I think Rails is trying to find account_id column in transactions table, because Transaction belongs_to :account. But I need both columns for :account to and from, as you see. So, maybe I need to change this belongs_to condition in Transaction model, but I don't know how.

Thanks for any ideas!

4

2 回答 2

1

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

has_many :transactions, :foreign_key => "from_account_id"

于 2013-06-01T17:28:03.307 回答
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 关系指南中的选项

于 2013-06-01T17:28:58.470 回答