1

私は借金を解決し、誰が誰に何を負っているのかなどを解決するアプリに取り組んでいます。

現在、次のように機能します。

create_table "debts", :force => true do |t|
  t.string   "amount"
  t.integer  "payer_id"
  t.integer  "payee_id"
  t.datetime "created_at", :null => false
  t.datetime "updated_at", :null => false
end

create_table "people", :force => true do |t|
  t.string   "name"
  t.integer  "bank"
  t.datetime "created_at", :null => false
  t.datetime "updated_at", :null => false
end

class Debt < ActiveRecord::Base
    attr_accessible :amount, :payee_id, :payer_id

    belongs_to :payee, :class_name => 'Person'
    belongs_to :payer, :class_name => 'Person'
 end

class Person < ActiveRecord::Base
    attr_accessible :amount, :payee_id, :payer_id

    has_many :debts_owed, :class_name => Debt, :foreign_key => "payee_id"
    has_many :debts_to_pay, :class_name => Debt, :foreign_key => "payer_id"
end

それは機能していますが、同じモデルへの複数の関連付けを表すより簡単な方法が必要であることを私は知っていますか?私はhas_and_belongs_to_manyを読んでいますが、これは正しいことのように見えますが、正直に言うと迷っています。

どんな助けでもいただければ幸いです!

ありがとう

4

2 に答える 2

1

HABTMがここで役立つとは思いません。

HABTMは、タグなど、多対多の関係が必要な状況向けです。一連のブログ投稿がある場合は、それらにタグを付けたいと思うかもしれません。ブログ投稿には多くのタグを付けることができ、タグは多くのブログ投稿で使用できます。

あなたの場合、そのような関係は起こっていません。私は正直なところ、あなたが持っている協会を設立するためのより良い方法があるとは思いません。

于 2012-06-16T23:01:42.823 に答える
0

For just two lines, that's not too much repetition, BUT if you really wanted to, you could do something like this:

[:payee, :payer].each {|f| belongs_to(f, :class_name => 'Person') }

So that's one line instead of two, but it's probably less clear to read and maintain. It might be worth it if you had a few more lines using the same class_name though.

于 2012-10-31T14:23:13.353 に答える