如何在 Rails 中访问父模型的实例变量?
我有两个通过 has_many/belongs_to 关联的模型。我在子模型中创建了一个类方法。但我无法弄清楚如何从类方法中访问父模型的实例方法。这是我想要做的事情的简化:
#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
我希望能够在 Rails 控制台中运行它并让它返回“John Doe”......但没有运气。有什么建议吗?
@user = User.first
@user.addresses.full_name
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 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. Any suggestions?
@user = User.first
@user.addresses.full_name
如果你对这篇内容有疑问,欢迎到本站社区发帖提问 参与讨论,获取更多帮助,或者扫码二维码加入 Web 技术交流群。
绑定邮箱获取回复消息
由于您还没有绑定你的真实邮箱,如果其他用户或者作者回复了您的评论,将不能在第一时间通知您!
发布评论
评论(2)
您将类继承与模型关系、类方法与实例方法混淆了。
失去“自我”。在“def self.full_name”中 - 它没有按照您的想法进行。然后将“父级”替换为“用户”。 Parent 为您提供了对 ActiveRecord::Base 的引用,这与您定义的关系无关。 “user”将为您提供该特定地址的 User 对象,这可能就是您正在寻找的。
前面的答案已经解释了为什么你不能在@user.addresses上调用“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.
这会返回一个数组,因此您需要从该数组中选择一个对象,假设该数组不为空。
这能达到什么目的呢?因为您可以从用户对象中获取全名,并且它不应该根据地址而更改:(
所以现在您可以从
@user
对象访问full_name
This returns an array so you need to pick a single object from the array, assuming the array is not empty.
What does this accomplish? Because you can get the full name off of the user object and it shouldn't change based on address :(
So now you can access
full_name
from the@user
object