Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

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.

like image 451
user738184 Avatar asked Jun 24 '11 14:06

user738184


1 Answers

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.

like image 169
nathanvda Avatar answered Oct 12 '22 22:10

nathanvda