【问题标题】:Access Rails proxy_association.owner from within association method从关联方法中访问 Rails proxy_association.owner
【发布时间】:2013-02-05 17:23:46
【问题描述】:

有没有办法从关联的方法中访问 proxy_association 对象?

例子:

class User < ActiveRecord:Base
  has_many :accounts
end

class Account < ActiveRecord:Base
  belongs_to :user

  def some_function
    # Here I want to access the same user object the association was called on
    # (that holds all already defined global variables), not a newly created object
    # through self.user (where all global variables are reset).

    proxy_association.owner
  end
end

如何从关联中访问调用关联的对象?不幸的是,self.user返回一个新对象,其中所有先前设置的变量都恢复为默认值。

【问题讨论】:

    标签: ruby-on-rails ruby-on-rails-3 associations rails-activerecord


    【解决方案1】:

    has_many 关联上使用:inverse_of 选项。这将在使用关联时连接内存中的两个模型。

    class User < ActiveRecord:Base
      has_many :accounts, inverse_of: :user
    end
    

    来源: http://api.rubyonrails.org/classes/ActiveRecord/Associations/ClassMethods.html#method-i-has_many

    【讨论】:

    • 哈哈,我也去过。很高兴我能帮上忙。
    猜你喜欢
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    相关资源
    最近更新 更多