开发者

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

I have two models which are associated via 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 pa开发者_Python百科rent 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. 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


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. Then replace "parent" with "user." Parent is giving you a reference to ActiveRecord::Base, which has nothing to do with the relationships you've defined. "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.

0

上一篇:

下一篇:

精彩评论

暂无评论...
验证码 换一张
取 消

最新问答

问答排行榜