如何初始化ActiveRecord无表模型?

时间:2011-03-04 11:41:17

标签: ruby-on-rails ruby ruby-on-rails-3 class

我正在使用Ruby on Rails 3,我想要使用ActiveRecord Tableless模型。

在我的模特中,我有:

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变量的debug \ inspect输出是

"#<Account >"

为什么呢?我应该如何正确地使用ActiveRecord无表格模型并使其正常工作?

2 个答案:

答案 0 :(得分: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"})

您是否已经尝试过这样做?

答案 1 :(得分: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