代码之家  ›  专栏  ›  技术社区  ›  ThoKra

基于字段值属于

  •  0
  • ThoKra  · 技术社区  · 16 年前

    我有一个表和条目,每个条目可以有不同的账户类型。我正在尝试根据的值定义并返回帐户 cindof

    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 也没什么不同 属于 名字。 有谁知道我想要什么吗?很难用英语解释。

    简洁

    2 回复  |  直到 16 年前
        1
  •  2
  •   Shadwell    16 年前

    你应该能够做你想做的多态关联。这不会打开 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 列和a account_type 列。然后,account对象的类型存储在extra type列中。

    obj.account = AccountPage.new
    

    或

    obj.account = AccountSite.new
    
        2
  •  0
  •   Matt Briggs    16 年前

    我将研究单表继承。不是百分之百肯定,但我认为这会解决你的问题 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