ActiveRecord ::没有表的基础

Dan*_*ark 22 activerecord ruby-on-rails-2

这出现了一段时间(在db中没有相应列的rails模型属性)但是看起来没有提到所提到的Rails插件(http://agilewebdevelopment.com/plugins/activerecord_base_without_table).有没有办法用ActiveRecord这样做?

如果没有,有没有办法在不使用ActiveRecord的情况下获得ActiveRecord验证规则?

当然,ActiveRecord希望表存在.

Joh*_*ley 39

这是我过去使用的一种方法:

app/models/tableless.rb中

class Tableless < ActiveRecord::Base
  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

  # Override the save method to prevent exceptions.
  def save(validate = true)
    validate ? valid? : true
  end
end
Run Code Online (Sandbox Code Playgroud)

app/models/foo.rb中

class Foo < Tableless
  column :bar, :string  
  validates_presence_of :bar
end
Run Code Online (Sandbox Code Playgroud)

脚本/控制台中

Loading development environment (Rails 2.2.2)
>> foo = Foo.new
=> #<Foo bar: nil>
>> foo.valid?
=> false
>> foo.errors
=> #<ActiveRecord::Errors:0x235b270 @errors={"bar"=>["can't be blank"]}, @base=#<Foo bar: nil>>
Run Code Online (Sandbox Code Playgroud)


Ste*_*sen 17

验证只是ActiveRecord中的一个模块.您是否尝试将它们混合到非ActiveRecord模型中?

class MyModel
  include ActiveRecord::Validations

  # ...
end
Run Code Online (Sandbox Code Playgroud)


blo*_*ess 9

我认为答案越多越好,因为这是Google搜索"没有桌子的rails 3.1模型"时的第一个结果之一

我在不使用ActiveRecord :: Base的同时实现了同样的功能,同时包含了ActiveRecord :: Validations

主要目标是使所有工作都在形成,而在下面我已经包含了一个样本付款,这些付款不会在任何地方保存,但仍然能够使用我们都知道和喜爱的验证进行验证.

class Payment
  include ActiveModel::Validations
  attr_accessor :cc_number, :payment_type, :exp_mm, :exp_yy, :card_security, :first_name, :last_name, :address_1, :address_2, :city, :state, :zip_code, :home_telephone, :email, :new_record

  validates_presence_of :cc_number, :payment_type, :exp_mm, :exp_yy, :card_security, :first_name, :last_name, :address_1, :address_2, :city, :state

  def initialize(options = {})
    if options.blank?
      new_record = true
    else
      new_record = false
    end
    options.each do |key, value|
      method_object = self.method((key + "=").to_sym)
      method_object.call(value)
    end
  end

  def new_record?
    return new_record
  end

  def to_key
  end

  def persisted?
    return false
  end
end
Run Code Online (Sandbox Code Playgroud)

我希望这对某人有所帮助,因为我今天花了几个小时试图解决这个问题.


Dim*_*tar 7

更新:对于Rails 3,这可以很容易地完成.在Rails 3+中,您可以使用新ActiveModel模块及其子模块.这应该现在有效:

class Tableless
  include ActiveModel::Validations

  attr_accessor :name

  validates_presence_of :name
end
Run Code Online (Sandbox Code Playgroud)

有关更多信息,您可以查看关于该主题的Railscast(或在AsciiCasts上阅读)以及Yehuda Katz 撰写的这篇博客文章.

老答复:

您可能需要将此添加到John Topley在之前的评论中提出的解决方案中:

class Tableless

  class << self
    def table_name
      self.name.tableize
    end
  end

end

class Foo < Tableless; end
Foo.table_name # will return "foos"
Run Code Online (Sandbox Code Playgroud)

如果需要,这会为您提供"假"表名.如果没有这种方法,Foo::table_name将评估为"tablelesses".