3

It looks like association extensions have changed quite a bit throughout Rails 3.x.

I need to access the proxy owner and the proxy target (i.e, the has_many object and the belongs_to object).

The most recent documentation says To use proxy_association.owner and proxy_association.target. However, this throws an method missing. I found some older references (can't find them now), saying that self.proxy_target would work. However this only seems to work intermittently and isn't reliable between my local environment and production (strange... I know).

Does anybody know where I can find more definitive answer on how to access the owner and target from within an association extension using Rails 3.0.10?

4

1 に答える 1

6

proxy_associationRails3.1の新機能です。レール3.0.x(および2.x)に相当するものはproxy_ownerおよびproxy_targetです。ただしproxy_target、関連付けが読み込まれている場合は、関連付けをキャッシュするインスタンス変数を返します。つまり、関連付けがまだ読み込まれていない場合は[]、コレクションの関連付けに戻ります。または言い換えれば、与えられた

class Bar < ActiveRecord::Base
  has_many :foos do
    def target_test
      proxy_target
    end
  end
end

それから

bar = Bar.first
bar.foos.target_test #=> []
bar.foos.inspect
bar.foos.target_test #=> [#<Foo id: 1 ...>]

load_targetを呼び出す前に呼び出すことで、ターゲットを強制的にロードできますproxy_target。それがすべて設定されているので、なぜこれが重要なのかわかりません-何かを呼び出すselfと、ターゲットに転送されます

于 2012-05-10T20:48:16.107 に答える