我正在使用Ruby on Rails 3,并希望公开一个ActiveRecord无表模型。如何初始化ActiveRecord无表模型?
在我的模型,我有:
class Account < ActiveRecord::Base
# The following ActiveRecord Tableless Model statement is from http://codetunes.com/2008/07/20/tableless-models-in-rails/
def self.columns()
@columns ||= [];
end
def self.column(name, sql_type = nil, default = nil, null = true)
columns << ActiveRecord::ConnectionAdapters::Column.new(name.to_s, default, sql_type.to_s, null)
end
attr_reader :id,
:firstname,
:lastname,
def initialize(attributes = {})
@id = attributes[:id]
@firstname = attributes[:firstname]
@lastname = attributes[:lastname]
end
end
如果在一个控制器,例如在application_controller.rb文件,我做的:
@new_account = Account.new({:id => "1", :firstname => "Test name", :lastname => "Test lastname"})
调试\检查@new_account
变量输出是
"#<Account >"
为什么?我应该如何正确地初始化ActiveRecord Tableless Model并使其工作?
它设置除id以外的所有字段(它是'nil') – rubyprince 2011-03-04 12:02:00
你说得对。我想'id'在ActiveRecord中有一个特殊的地位。我认为这只会在记录被保存在某个数据库后才会设置。 – Wukerplank 2011-03-04 12:08:16
@Wukerplank你的代码有效,但'attr_reader'和'attr_writer'呢?如果我尝试设置更多,我会遇到一些麻烦,例如'@ new_account.lastname'。你有什么建议(出于安全原因)? – user502052 2011-03-04 12:15:50