【问题标题】:Cloning attributes of one object to the other将一个对象的属性克隆到另一个对象
【发布时间】:2026-02-19 03:00:02
【问题描述】:

我有两个模型 Content 和 ContentType。每个内容(类而不是对象)都有其关联的 ContentType 并且 ContentType 基本上包含一些可以使用在线表单设置的属性,然后可以在视图中使用这些属性来显示/隐藏一些内容对象的属性。

创建一个新的 Content 对象(例如:@c = Content.new)后,我可以使用以下方法检索关联的 ContentType:

课程内容 定义内容类型 @content_type ||= ContentType.find_by_name(self.class.to_s) 结尾 结束

然后我可以使用 @c.content_type.xxx 查询 ContentType 属性,但是有没有办法直接访问 ContentType 属性,就好像它们是 @c 属性一样,而不使用 method_missing 选项。基本上不是做@c.content_type.has_title?我想问@c.has_title?。有没有办法将 ContentType 属性克隆到 @c 上?

提前致谢。

【问题讨论】:

    标签: ruby-on-rails


    【解决方案1】:

    你可以使用委托方法

    has_one :user
    delegate :name, :name=, :email, :email=, :to => :user 
    

    这至少要好一些,因为 ContentType 可以隐藏。

    如果 ContentType 也可以为 nil,您还可以传递一个 :allow_nil => true 选项,让您免于令人讨厌的“Cant call nil.xxx”错误。

    【讨论】:

      最近更新 更多