2011-08-21 4 views
2

HABTM関係に関するメタデータを追加する必要があります。私はこれを達成するためにhas_many:throughの関係を使いたかったのですが、必ずしもそうではありません。ここでは単純化の問題がある:has_many:through - スルー関係にメタデータを追加する

class Customer < ActiveRecord::Base 
    has_many :customer_teddy_bears 
    has_many :teddy_bears, :through => :customer_teddy_bears 
end 

class CustomerTeddyBear < ActiveRecrod::Base 
    belongs_to :customer 
    belongs_to :teddy_bear 
    attr_accesible :most_favoritest # just to show it exists, boolean 
end 

class TeddyBear < ActiveRecord::Base 
    has_many :cusomter_teddy_bears 
end 

だから私は何をする必要があるかテディベアが私の顧客に負担の追加を開始され、テディベアは、データの固定セットされ、fireman_bear、doctor_bear、dominatrix_bearを言うことができます。どの顧客も一種のテディベアを所有していると主張することができますが、最も好きなクマはどれですか?私はすべての顧客の間でグローバルに共有されているので、私は熊モデルを変更できないので、(ほかのメタデータの中でも)CustomerTeddyBearにメタデータを追加しています。

問題は次のように動作しないことです。

customer = Customer.new # new record, not yet saved, this must be handled. 
customer.teddy_bears << fireman_bear 
customer.teddy_bears << doctor_bear 
# now to set some metadata 
favoritest_record = customer.customer_teddy_bears.select{|ctb| ctb.teddy_bear == doctor_bear}.first 
favoritest_record.most_favoritest = true 

上記のコードは、customer_teddy_bearsエントリがデータベースにレコードを作成するときに保存時に作成されるため、機能しません。これを行うための別の仕組みがありますか?

レールに組み込まれた「自動化」は何も存在しない場合、私はちょうど私がcustomer_teddy_bearsを選択して、手動で関連付けを作成するとともに

def teddy_bears 
    self.customer_teddy_bears.map(&:teddy_bear) 
end 

のような技術を使用した場合、手動でteddy_bears含めることによって、この関係を管理する必要があり、ないだろうa:through関係を使用します。

これはすべて、がCustomerオブジェクトで実行される前に発生する必要があります。したがって、メモリ内にあるすべての関連メタデータを設定する必要があります。

勧告は、私はあなたが単純にこれを行うことができます#RubyOnRails

ctb = customer.customer_teddy_bears.build({:customer => customer, :teddy_bear => fireman_bear}) 
ctb2 = customer.customer_teddy_bears.build({:customer => customer, :teddy_bear => doctor_bear}) 
... 
ctb.most_favoritest = true 

答えて

0

私は手動でCustomerTeddyBearオブジェクトを構築し、顧客の両方を設定しているに頼ることを余儀なくされたソリューション、 teddy_bear、most_favoritestです。基本的には、ほとんどの場合、アクセスは少なくともロジックではcustomer.customer_teddy_bears.map(&:teddy_bear)で、レコードがまだ保存されていない可能性があります。それ以外の場合はcustomer.teddy_bearsにショートカットします。

1

からもらっ:

customer = Customer.new # new record, not yet saved, this must be handled. 
customer.teddy_bears << fireman_bear 
customer.teddy_bears << doctor_bear 
customer.save 

fav = CustomerTeddyBear.where(:customer_id => customer.id, :teddybear_id => doctor_bear.id) 
fav.most_favoritest = true 
fav.save 
+0

私はそれを行うことはできません。 fav.most_favoritest = trueが設定される前に保存が実行されることはありません。 –

関連する問題