jon*_*nes 2 ruby-on-rails associations ruby-on-rails-3 rails-activerecord
有没有一种方法可以从关联的方法中访问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
Run Code Online (Sandbox Code Playgroud)
如何访问从关联中调用关联的对象?不幸的是,self.user
返回一个新对象,其中所有先前设置的变量都恢复为默认值。
小智 5
使用关联:inverse_of
上的选项has_many
。使用关联时,这将连接内存中的两个模型。
class User < ActiveRecord:Base
has_many :accounts, inverse_of: :user
end
Run Code Online (Sandbox Code Playgroud)
来源:http : //api.rubyonrails.org/classes/ActiveRecord/Associations/ClassMethods.html#method-i-has_many
归档时间: |
|
查看次数: |
1026 次 |
最近记录: |