I have two models Content and ContentType. Each Content (class not object) has its associated ContentType and ContentType basically holds some attributes that could be set using online form, which then can be used in the views to show/hide some of the content objects attributes.
我有两个模型Content和ContentType。每个Content(类不是对象)都有其关联的ContentType,ContentType基本上包含一些可以使用在线表单设置的属性,然后可以在视图中使用这些属性来显示/隐藏一些内容对象属性。
After creating a new Content object (ex: @c = Content.new) I could retrieve the associated ContentType using:
在创建新的Content对象(例如:@c = Content.new)之后,我可以使用以下方法检索关联的ContentType:
class Content def content_type @content_type ||= ContentType.find_by_name(self.class.to_s) end end
class Content def content_type @content_type || = ContentType.find_by_name(self.class.to_s)end end
I could then query the ContentType attributes using @c.content_type.xxx but is there any way to directly access the ContentType attributes as if they are @c attributes without using the method_missing option. Basically instead of doing @c.content_type.has_title? I would like to ask @c.has_title?. Is there any way to clone the ContentType attributes onto @c?
然后,我可以使用@ c.content_type.xxx查询ContentType属性,但有没有办法直接访问ContentType属性,就像它们是@c属性而不使用method_missing选项一样。基本上不是做@ c.content_type.has_title?我想问@ c.has_title?有没有办法将ContentType属性克隆到@c?
thanks in advance.
提前致谢。
1 个解决方案
#1
You can use the delegate method
您可以使用委托方法
has_one :user
delegate :name, :name=, :email, :email=, :to => :user
This is at least somewhat better, as the ContentType can be hidden.
这至少要好一些,因为可以隐藏ContentType。
Also you can pass an :allow_nil => true
option that saves you from pesky "Cant call nil.xxx" errors if the ContentType can be nil as well.
您还可以传递:allow_nil => true选项,如果ContentType也可以为零,则可以避免讨厌“Cant call nil.xxx”错误。
#1
You can use the delegate method
您可以使用委托方法
has_one :user
delegate :name, :name=, :email, :email=, :to => :user
This is at least somewhat better, as the ContentType can be hidden.
这至少要好一些,因为可以隐藏ContentType。
Also you can pass an :allow_nil => true
option that saves you from pesky "Cant call nil.xxx" errors if the ContentType can be nil as well.
您还可以传递:allow_nil => true选项,如果ContentType也可以为零,则可以避免讨厌“Cant call nil.xxx”错误。