简体   繁体   中英

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.

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:

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

a debug\\inspect output of the @new_account variable is

"#<Account >"

Why? How I should inizialize properly that ActiveRecord Tableless Model and make it to work?

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. 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

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

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