0

エントリを含むテーブルがあり、各エントリは異なるアカウント タイプを持つことができます。の値に基づいてアカウントを定義して返そうとしていますcindof

アカウントの種類ごとに 1 つのテーブルがaccount_siteあり、account_page. だからレギュラーbelongs_toじゃ無理。

次のようなものを返す方法はありますか?

belongs_to :account, :class_name => "AccountSite", :foreign_key => "account_id" if cindof = 1
belongs_to :account, :class_name => "AccountPage", :foreign_key => "account_id" if cindof = 2

メソッドでもそれをやろうとしましたが、運がありません。account違うbelongs_to名前ではなく、 1 つだけにしたいのです。私が欲しいものを理解できる人はいますか?英語で説明するのは難しい。

ターウ

4

2 に答える 2

2

多形の関連付けを使用して、やりたいことができるはずです。cindofこれはデフォルトではオンになりませんが、問題にならない場合があります。

class ObjectWithAccount < ActiveRecord::Base
  belongs_to :account, :polymorphic => true
end

class AccountSite < ActiveRecord::Base
  has_many :objects_with_accounts, 
        :as => :account, 
        :class_name => 'ObjectWithAccount'
end

class AccountPage < ActiveRecord::Base
  has_many :objects_with_accounts, 
        :as => :account, 
        :class_name => 'ObjectWithAccount'
end

account_id列と列の両方が必要になりaccount_typeます。アカウントオブジェクトのタイプは、追加のタイプ列に格納されます。

これにより、次のことが可能になります。

obj.account = AccountPage.new

また

obj.account = AccountSite.new
于 2010-09-09T13:37:22.890 に答える
0

単一テーブルの継承を調べます。100%確実ではありませんが、問題は解決すると思いますhttp://code.alexreisner.com/articles/single-table-inheritance-in-rails.html

それが良くない場合、これを自分で実装するのはそれほど難しくありません。

def account
  case self.cindof
    when 1 then AccountSite.find self.account_id
    when 2 then AccountPage.find self.account_id
  end
end
于 2010-09-09T13:12:01.280 に答える