2011-03-04 136 views
0

我正在使用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並使其工作?

回答

1

根據這一博客帖子它會看起來像這樣:

class Account < ActiveRecord::Base 

    class_inheritable_accessor :columns 

    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 

    column :id, :integer 
    column :firstname, :string 
    column :lastname, :string 

end 

然後:

@new_account = Account.new({:id => "1", :firstname => "Test name", :lastname => "Test lastname"}) 

你已經嘗試這樣呢?

+0

它設置除id以外的所有字段(它是'nil') – rubyprince 2011-03-04 12:02:00

+0

你說得對。我想'id'在ActiveRecord中有一個特殊的地位。我認爲這隻會在記錄被保存在某個數據庫後纔會設置。 – Wukerplank 2011-03-04 12:08:16

+0

@Wukerplank你的代碼有效,但'attr_reader'和'attr_writer'呢?如果我嘗試設置更多,我會遇到一些麻煩,例如'@ new_account.lastname'。你有什麼建議(出於安全原因)? – user502052 2011-03-04 12:15:50

0

我認爲,你不需要擴展ActiveRecord :: Base類。 您可以編寫自己的模型類是這樣的

 
# models/letter.rb 
class Letter 
    attr_reader :char 

    def self.all 
    ('A'..'Z').map { |c| new(c) } 
    end 

    def self.find(param) 
    all.detect { |l| l.to_param == param } || raise(ActiveRecord::RecordNotFound) 
    end 

    def initialize(char) 
    @char = char 
    end 

    def to_param 
    @char.downcase 
    end 

    def products 
    Product.find(:all, :conditions => ["name LIKE ?", @char + '%'], :order => "name") 
    end 
end 

# letters_controller.rb 
def index 
    @letters = Letter.all 
end 

def show 
    @letter = Letter.find(params[:id]) 
end 

我希望這會幫助你。 參考:http://railscasts.com/episodes/121-non-active-record-model

+0

我繼承自 user502052 2011-03-04 11:57:52

+0

我認爲他需要在列方法中使用ActiveRecord的sql_connections方法..這可能是他爲什麼要從ActiveRecord擴展的原因。 – rubyprince 2011-03-04 11:58:24

+0

正如@rubyprince所說。 – user502052 2011-03-06 21:35:50