gpt4 book ai didi

ruby-on-rails - 从关联方法中访问 Rails proxy_association.owner

转载 作者:行者123 更新时间:2023-12-02 05:15:34 27 4
gpt4 key购买 nike

有没有办法从关联方法中访问 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返回一个新对象,其中所有先前设置的变量都返回到默认值。

最佳答案

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

关于ruby-on-rails - 从关联方法中访问 Rails proxy_association.owner,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/14713281/

27 4 0
Copyright 2021 - 2024 cfsdn All Rights Reserved 蜀ICP备2022000587号
广告合作:1813099741@qq.com 6ren.com