2017-01-26 9 views
0

私は以下のレールモデルを持っています。継承を使用して多形関係を取得するには?

class Service < ApplicationRecord 
    self.table_name ='service' 
end 

class ChildA < Service 
    has_many :charges 
end 

class ChildB < Service 
    self.table_name = "childb_table" 
    has_many :charges 
end 

class Charges < ApplicationRecord 
    :belongs_to chargeable, polymorphic: true 
end 
# code using this 
a = ClassB.new.save 
charge = Charges.new.save 
a.charges.add(a) # this adds the column with the class name 'Service' 

私は、オブジェクトを保存しようとしたがchargeable_typeフィールドは常に基本クラスservice、決して子クラスとして設定されています。

どうすればこの問題を回避できますか?

+1

は 'べきではない:charges':has_manyのをcharges'ラインは' has_manyのこと? ( 'belongs_to'行と同じです)また、ここで何が起こっているのか全く分かりません。どのオブジェクトを保存しようとしていますか?あなたはオブジェクトを保存するために使用しているコードを表示できますか?私はここにペーストされたものでは確信が持てませんが、あなたはSTIを探しているかもしれません(https://eewang.github.io/blog/2013/03/12/how-and-when-to-use-single-table -inheritance-in-rails /)を使用します。 – Glyoko

答えて

0

は、私は解決策がrails documentationであると思う:

は、単一のテーブル 継承(STI)との組み合わせで多型の関連付けを使用して少しトリッキーです。 へのアソシエーションが期待通りに機能するように、STI モデルの基本モデルをポリモーフィックアソシエーションのtypeカラムに格納してください。上記の資産例と を続行するには、STIの投稿テーブルを使用するゲスト投稿とメンバー の投稿があるとします。この場合、投稿テーブルに タイプの列が必要です。

注:添付可能な を割り当てるときは、attachable_type =メソッドが呼び出されています。 attachableのclass_nameはStringとして渡されます。

class Asset < ActiveRecord::Base 
    belongs_to :attachable, polymorphic: true 

    def attachable_type=(class_name) 
    super(class_name.constantize.base_class.to_s) 
    end 
end 

class Post < ActiveRecord::Base 
    # because we store "Post" in attachable_type now dependent: :destroy will work 
    has_many :assets, as: :attachable, dependent: :destroy 
end 

class GuestPost < Post 
end 

class MemberPost < Post 
end 
+0

添付ファイル型は常にbase_class名で呼び出されます。現在のクラス名を使用して呼び出されます。 "GuestPost" – sheki

+0

次に、各サブクラスの 'attachable_type ='メソッドをオーバーライドし、必要なクラス名を返します。 – ReggieB

+1

これをやってみましたが、\ o/ – sheki

関連する問題