简体   繁体   English

如何在Rails中访问父模型的实例变量?

[英]How do I access instance variables of parent model in Rails?

I have two models which are associated via has_many/belongs_to. 我有两个通过has_many / belongs_to关联的模型。 I've created a class method within the child model. 我在子模型中创建了一个类方法。 But I can't figure out how to access the instance methods of the parent model from within the class method. 但是我无法弄清楚如何从类方法中访问父模型的实例方法。 Here's a simplification of what I'm trying to do: 这是我要做的事情的简化:

#User model
class User < ActiveRecord::Base
    has_many :addresses

    def first_name
        "John"
    end

    def last_name
        "Doe"
    end
end

#Address model
class Address < ActiveRecord::Base
    belongs_to :user

    def self.full_name
        parent.first_name + " " + parent.last_name
        #returns full name of parent "John Doe"
    end
end

I'd like to be able to run this in the Rails console and have it return "John Doe"... but no luck. 我希望能够在Rails控制台中运行此程序,并使它返回“ John Doe” ...但没有运气。 Any suggestions? 有什么建议么?

@user = User.first
@user.addresses.full_name
@user.addresses.full_name

This returns an array so you need to pick a single object from the array, assuming the array is not empty. 这将返回一个数组,因此您需要从该数组中选择一个对象,并假设该数组不为空。

@user.address.first.full_name

What does this accomplish? 这有什么作用? Because you can get the full name off of the user object and it shouldn't change based on address :( 因为您可以获得用户对象的全名,所以它不应根据地址而改变:(

class User < ActiveRecord::Base
    has_many :addresses

    def first_name
        "John"
    end

    def last_name
        "Doe"
    end

    def full_name
        self.first_name + " " + self.last_name
    end 
end

So now you can access full_name from the @user object 所以现在您可以从@user对象访问full_name

@user.full_name

You are confusing class inheritence with Model relationships, and class methods with instance methods. 您将类继承与模型关系,类方法与实例方法混淆。

Lose the "self." 失去“自我”。 in "def self.full_name" - it's not doing what you think. 在“ def self.full_name”中-它没有按照您的想法进行。 Then replace "parent" with "user." 然后将“ parent”替换为“ user”。 Parent is giving you a reference to ActiveRecord::Base, which has nothing to do with the relationships you've defined. 父母为您提供了ActiveRecord :: Base的引用,该引用与您已定义的关系无关。 "user" will give you that particular address's User object, which is probably what you're looking for. “用户”将为您提供该特定地址的用户对象,这可能就是您要查找的对象。

The previous answer has already gone into why you can't call "full_name" on @user.addresses. 前面的答案已经解释了为什么不能在@ user.addresses上调用“ full_name”。

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM