我正在使用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