Satynos
Satynos

Reputation:

Cloning attributes of one object to the other

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.

After creating a new Content object (ex: @c = Content.new) I could retrieve the associated ContentType using:

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?

thanks in advance.

Upvotes: 1

Views: 168

Answers (1)

nasmorn
nasmorn

Reputation: 2150

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.

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.

Upvotes: 1

Related Questions