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

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

As required, when I submit a WidgetFeature object, I have to add the file_name to it for this related function.
There are two ways in it:

  • When sending an object, do the following:
 widget_feature_object[:feature_name] = feature_name_value 

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

2. Create feature_name a Virtual attribute in the WidgetFeature model, and then create retrieval and configuration methods for it.

From what I know, you should use virtual attributes if you want to create a different view than the fields actually present in the model (for example, Full Name = First Name and Last Name).
Does the same thing apply here?

Also , does Rails do some object caching, which might come in handy when using virtual attributes rather than the first time?

What are the pros and cons of each approach and which one is best suited to my requirements? Thank you very much.

+4
source share
3 answers

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

In WidgetFeature I would write:

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

then you can write

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

Hope this helps.

+5
source

Use attr_accessor if you want to set the method. Otherwise, just use common functions.

If you want to cache, check out memoization

+2
source

I'm not sure why you insist on using the [] notation to access your attributes, but in one of the following ways:

 def [](attr) if attr == :feature feature # Return the associated feature object else super # Call ActiveRecord::Base#[] end end 

Of course, you could come to terms with some metaprogramming to automatically identify valid associations.

I personally don't like monkeypatching this way, but since [] is a simple method, you'll probably be safe. The surface is that it allows you widget_feature [: feature] [: name] and even widget_feature [: feature] [: name] =

You get all the ActiveRecord functionality that you could call using widget_feature.feature.

0
source

All Articles