简体   繁体   English

如何使该ActiveRecord无表模型生效?

[英]How can I inizialize that ActiveRecord Tableless Model?

I am using Ruby on Rails 3 and I would like to inizialize an ActiveRecord Tableless Model. 我正在使用Ruby on Rails 3,并且想初始化ActiveRecord无表模型。

In my model I have: 在我的模型中,我有:

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

If in a controller, for example in the application_controller.rb file, I do: 如果在控制器中,例如在application_controller.rb文件中,则执行以下操作:

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

a debug\\inspect output of the @new_account variable is @new_account变量的debug \\ inspect输出为

"#<Account >"

Why? 为什么? How I should inizialize properly that ActiveRecord Tableless Model and make it to work? 我应该如何正确地初始化该ActiveRecord无表模型并使之正常工作?

According to that blog post it would have to look like this: 根据该博客文章,它必须看起来像这样:

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

And then: 接着:

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

Did you already try it like that? 您已经尝试过了吗?

I my view, you don't need to extend ActiveRecord::Base class. 我认为,您不需要扩展ActiveRecord :: Base类。 You can write your own model class something like this 您可以编写自己的模型类,如下所示

# 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

I hope it will help you. 希望对您有帮助。 Reference: http://railscasts.com/episodes/121-non-active-record-model 参考: http : //railscasts.com/episodes/121-non-active-record-model

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM