Reputation: 1465
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
Upvotes: 0
Views: 1560
Reputation: 20232
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
Upvotes: 1