How can I inizialize that ActiveRecord Tableless M

2019-09-03 16:32发布

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?

2条回答
Ridiculous、
2楼-- · 2019-09-03 16:38

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

查看更多
Rolldiameter
3楼-- · 2019-09-03 16:51

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?

查看更多
登录 后发表回答