的ActiveRecord :: Base的无表 [英] ActiveRecord::Base Without Table
问题描述
这想出了一个位前(没有相应的数据库列轨道模型属性),但它看起来像提到的是Rails插件不能保持(<一href="http://agilewebdevelopment.com/plugins/activerecord_base_without_table">http://agilewebdevelopment.com/plugins/activerecord_base_without_table )。有没有办法做到这一点用ActiveRecord原样?
This came up a bit ago ( rails model attributes without corresponding column in db ) but it looks like the Rails plugin mentioned is not maintained ( http://agilewebdevelopment.com/plugins/activerecord_base_without_table ). Is there no way to do this with ActiveRecord as is?
如果没有,有没有什么办法让ActiveRecord的验证规则,而不使用ActiveRecord的?
If not, is there any way to get ActiveRecord validation rules without using ActiveRecord?
ActiveRecord的希望表中存在,当然。
ActiveRecord wants the table to exist, of course.
推荐答案
这是我在过去使用的方法:
This is an approach I have used in the past:
在应用/型号/ 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
在应用/型号/ foo.rb
class Foo < Tableless
column :bar, :string
validates_presence_of :bar
end
在脚本/控制台
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>>
这篇关于的ActiveRecord :: Base的无表的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!