hajpoj
hajpoj

Reputation: 13379

Dynamically added hash properties to Rails Model instance object?

There is a model

class PlaylistModel < ActiveRecord::Base
    /* code */
end

And then in a controller action there is code like this

PlaylistController < ActionController::Base
  def a_action
    @item = Playlist.find(10)
    @item[:visited] = true     
  end
end

However there is no visited attribute defined in PlaylistModel (or in the schema for the playlist table)! It looks like a new attribute is being dynamically added to the object. Is this what is going on and where is all this functionality defined / where can I read more about it.

Thanks for the help!

Upvotes: 8

Views: 9359

Answers (2)

Abram
Abram

Reputation: 41874

I think what you're looking for though is virtual attributes... which can be defined in the model http://railscasts.com/episodes/16-virtual-attributes

Upvotes: 2

PinnyM
PinnyM

Reputation: 35533

This is the attribute setter shortcut as explained here. It is pretty much equivalent to:

@item.attributes[:visited] = true

Upvotes: 13

Related Questions