Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

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!

like image 484
hajpoj Avatar asked Sep 20 '12 20:09

hajpoj


2 Answers

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

@item.attributes[:visited] = true
like image 136
PinnyM Avatar answered Nov 10 '22 08:11

PinnyM


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

like image 24
Abram Avatar answered Nov 10 '22 08:11

Abram