I'm really confused about virtual attributes in Rails 3.2 and all my research haven't help making things clearer.
# input model
class Input < ActiveRecord::Base
# Attributes --------------------
attr_accessible :title, :parent
attr_accessor :parent
def parent=(id)
wrtite_attribute(:parent, id.to_i)
self.parent = id.to_i
self[:parent] = id.to_i
@parent = id.to_i # seems to be the only one working. Why?
end
end
# inputs controller
class InputsController < ApplicationController
def new
@input = Input.new({
start_date: @current_scope_company.creation_date,
parent: 'bla'
})
@input.parent = 'bla'
@input[;parent] = 'bla'
end
end
# inputs table
create_table "inputs", :force => true do |t|
t.string "title"
t.datetime "created_at", :null => false
t.datetime "updated_at", :null => false
end
Above, I have compiled pretty much all the alternatives I found on the internet. It is NOT the code I run, just couple versions of the same thing. Though, whatever I try, I get the following warning:
DEPRECATION WARNING: You're trying to create an attribute 'parent'. Writing arbitrary attributes on a model is deprecated. Please just use 'attr_writer' etc.
Sometimes, I even get a stack level too deep
. I'd love to understand how attributes work.
1/ attr_accessor
is attr_writer
plus attr_reader
right? Why am I asked to use attr_writer
in the warning?
2/ How am I supposed to write attributes from the model (and why)
3/ How am I supposed to write attributes from the controller (and why)
Thanks a lot!
Update
After further test, it looks like the proper way to do it is @parent = id.to_i
. I would still love to get explanation why. I'm really confused why self.
wouldn't work.