ActiveRecord::Base 无表 [英] ActiveRecord::Base Without Table
问题描述
这是在不久前出现的(在 db 中没有相应列的 Rails 模型属性),但看起来提到的 Rails 插件是未维护( 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:
在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
在app/models/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屋!