So I am wondering if there is a better way of doing this. I have a parent class that has three 1 to 1 relationships, children.
所以我想知道是否有更好的方法来做到这一点。我有一个父类,有三个1对1的关系,孩子。
class Parent
has_one :child_one
has_one :child_two
has_one :child_three
...
end
Then within each child object I state belongs_to :parent
, now ChildOne has attribute1
, attribute2
, ...
, attribute30
etc.
然后在每个子对象中我声明belongs_to:parent,现在ChildOne有attribute1,attribute2,...,attribute30等。
I am using a gem that uses yaml to build calculations, but it can only access the table or model of the Parent class. It means that all the attributes i need from the ChildOne class I'll have to pull like this
我正在使用一个使用yaml构建计算的gem,但它只能访问Parent类的表或模型。这意味着我需要从ChildOne类中获取所有属性,我必须像这样
def calculation_one
cal_one = self.child_one.attribute1
end
and onward. This would mean that I would have a model that's freakin fat just linking children attributes. Is there a better way of doing this?
然后继续这意味着我会有一个只是链接儿童属性的模型。有更好的方法吗?
Update
更新
What i am looking for is a way to basically attr_accessor
a subclass?
我正在寻找的是一种基本上attr_accessor子类的方法?
class Parent
attr_accessor :child_one, :attribute1
end
person = Parent.new
person.attribute1 = "awesome"
person.attribute1 # => "awesome"
1 个解决方案
#1
3
I think what you're looking for is the Delegate
module in rails : you can call delegate
to let a related model respond to a method call like that :
我认为你要找的是rails中的Delegate模块:你可以调用delegate让相关模型响应方法调用:
class Parent < ActiveRecord::Base
has_one :child_one
delegate :attribute1, to: :child_one
end
Full documentation : http://apidock.com/rails/Module/delegate
完整文档:http://apidock.com/rails/Module/delegate
#1
3
I think what you're looking for is the Delegate
module in rails : you can call delegate
to let a related model respond to a method call like that :
我认为你要找的是rails中的Delegate模块:你可以调用delegate让相关模型响应方法调用:
class Parent < ActiveRecord::Base
has_one :child_one
delegate :attribute1, to: :child_one
end
Full documentation : http://apidock.com/rails/Module/delegate
完整文档:http://apidock.com/rails/Module/delegate