如何创建Rails 3中ActiveRecord的无表格模型 [英] How to create ActiveRecord tableless Model in Rails 3

查看:147
本文介绍了如何创建Rails 3中ActiveRecord的无表格模型的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

我想创建一个活动记录无表格的模型。我user.rb看起来像这样

 类用户的LT;的ActiveRecord :: Base的

  class_inheritable_accessor:列

  高清self.columns
    @columns || = [];
  结束

  高清self.column(姓名,sql_type =零,默认值=零,空=真)
    列<< ActiveRecord的:: ConnectionAdapters :: Column.new(
      name.to_s,
      默认,
      sql_type.to_s,
      空值
    )
  结束


  列:姓名,:文本
  专栏:例外:文本
  连载:异常
结束
 

在创建在控制器中的新对象

@user = User.new

我收到错误

Mysql2 ::错误:表'Sampledb.users不存在:SHOW FIELDS FROM 用户

解决方案

 类无表格

  包括加载ActiveModel ::验证
  包括加载ActiveModel ::转换
  延长加载ActiveModel ::命名

  高清self.attr_accessor(*瓦尔)
    @属性|| = []
    @ attributes.concat商(VAR)
    超
  结束

 高清self.attributes
   @属性
 结束

 高清初始化(属性= {})
   属性和放大器;&安培; attributes.each做|名称,值|
     送(#{名} =value)如果的respond_to? name.to_sym
   结束
 结束

高清坚持?
  假
结束

高清self.inspect
  #<#{self.to_s}#{self.attributes.collect {| E |:#{É}。加入('')}>中
结束

结束
 

I am trying to create a Active Record tableless Model. My user.rb looks like this

class User < 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 :name, :text
  column :exception, :text
  serialize :exception      
end

When creating the new object in controller

@user = User.new

I am getting the error

Mysql2::Error: Table 'Sampledb.users' doesn't exist: SHOW FIELDS FROM users

解决方案

class Tableless

  include ActiveModel::Validations
  include ActiveModel::Conversion
  extend ActiveModel::Naming

  def self.attr_accessor(*vars)
    @attributes ||= []
    @attributes.concat( vars )
    super
  end

 def self.attributes
   @attributes
 end

 def initialize(attributes={})
   attributes && attributes.each do |name, value|
     send("#{name}=", value) if respond_to? name.to_sym 
   end
 end

def persisted?
  false
end

def self.inspect
  "#<#{ self.to_s} #{ self.attributes.collect{ |e| ":#{ e }" }.join(', ') }>"
end

end

这篇关于如何创建Rails 3中ActiveRecord的无表格模型的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆