views:

18

answers:

1

Hi all,

I've got a "word" model in my rails app. In the index action of my words controller, I grab a set of words from my database and look up their definitions. I do not store definitions in my database and do not wish to store them there. However, I would like the controller to add the definition for each word to the word object before handing it to the view.

In other words, my "word" objects contain the following fields:

t.integer  "user_id"
t.text     "notes"
t.datetime "created_at"
t.datetime "updated_at"
t.string   "word_name"

The words controller does something like

@words = current_user.words

And the view can display things like

<% @words.each do |w| %>
    <%= w.word_name %>
    <%= w.notes %>
<% end %>

I would like to have the controller do

@words.each do |w|
    w.definition = "blah"
end

and then display this in my view:

<%= word.definition %>

However objects of type Word don't have a "definition" field, so the above does not work. Do you have suggestions for the cleanest way to accomplish this?

Thanks

+1  A: 

add a virtual attribute to the word model.

http://railscasts.com/episodes/16-virtual-attributes

something as simple as this should do it

class Word < ActiveRecord::Base
  attr_accessor :definition

   .... rest of class.... 
end 
Doon
Thanks, this works great. I'm also using the to_json method on my object, and it turns out that to_json does not pick up virtual attributes. The following post was helpful on working around that: http://stackoverflow.com/questions/1563118/activerecord-virtual-attributes-treaded-as-a-record-attributes
stupakov