Search code examples
ruby-on-railsruby-on-rails-3cachingvirtual-attributememorycache

When to use a virtual attribute or pass data in a hash in Rails 3


In my application, I have a Widget model, a Feature model with a has_many through association by WidgetFeature table.

As per the requirements, when I am sending a WidgetFeature object, I should append the feature_name to it as well, for the given feature associated.
There are two ways of going at it:

  1. While sending the object, do this:
widget_feature_object[:feature_name] = feature_name_value

and then I can access it in my controller or view, by widget_feature_object[:feature_name] because an object has (key, value) pairs, so I can add another too.

2 . Make feature_name a Virtual Attribute in WidgetFeature model, and then create getter and setter methods for it.

From what I know, that you should use virtual attributes when you want to create a different view different from the fields actually present in the model (e.g Full name = First name + Last name).
Does the same thing fits in here too?

Also, does Rails do some caching on objects, that might get in useful when you use virtual attributes and not when I use the first approach?

What are the pros and cons of each approach and which one suits the best as per my requirements? Thanks a lot.


Solution

  • I would propose an alternative approach: use delegate (documentation).

    In the WidgetFeature I would write:

    class WidgetFeature
    
      belongs_to :feature
    
      delegate :name, :to => :feature, :prefix => true
    end
    

    then you will be able to write

    f = WidgetFeature.first
    
    f.feature_name #will return f.feature.name
    

    Hope this helps.