stupakov
stupakov

Reputation: 1465

Rails: adding a field to a model-based object before passing it to the view

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

Answers (1)

Doon
Doon

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

Related Questions