Ruby on rails Rails模式创建问题
我正在使用Jruby和rails 2.2.2。我的问题是,有一个迁移没有正确写入数据库架构 以下是我的迁移:Ruby on rails Rails模式创建问题,ruby-on-rails,jruby,migration,activerecord-jdbc,Ruby On Rails,Jruby,Migration,Activerecord Jdbc,我正在使用Jruby和rails 2.2.2。我的问题是,有一个迁移没有正确写入数据库架构 以下是我的迁移: class CreateNotes < ActiveRecord::Migration def self.up create_table(:notes, :options => 'ENGINE=MyISAM') do |t| t.string :title t.text :body t.timestamps end
class CreateNotes < ActiveRecord::Migration
def self.up
create_table(:notes, :options => 'ENGINE=MyISAM') do |t|
t.string :title
t.text :body
t.timestamps
end
execute "alter table notes ADD FULLTEXT(title, body)"
end
我有两个问题:
- 如何将
放入模式中'ENGINE=MyISAM'
- 为什么我的execute语句变成了
?如何强制迁移将其保留为execute语句add_index“notes”、[“title”、“body”]、:name=>“title”
感谢Christian Lescuyer的回答。然而,当我尝试这一点时,一切都没有改变。我取消了config.active\u记录的注释。。。但是,我的模式没有改变。我已经在jruby和ruby 1.8.6以及rails 2.2.2和edge rails中尝试过这一点,但模式中没有任何更改。谁能告诉我我做错了什么吗?因为我使用外键约束,所以我使用SQL格式进行迁移。在environment.rb中: 克里斯蒂安是对的 做 config.active\u record.schema\u format=:sql in environment.rb 但是,您必须使用不同的模式转储格式和文件位置。尝试进行迁移并查找“schema.sql”而不是scehema.rb
所有这一切的原因是,方案文件的要点是一个数据库非特定(适用于所有类型的数据库)文件。因此,当您使用仅通过未经授权的execute语句在mysql上工作的功能时,它们不能被嵌入schema.rb中,我也希望在设置后看到一个新的.sql文件出现在“rake db:migrate”之后
config.active_record.schema_format = :sql
在config/environment.rb中
然而,显然这不是它的工作原理。我必须明确地这样做才能得到一个db/[development | test | production]_structure.sql文件:
rake db:structure:dump
要使用SQL变量进行测试(而不是schema.rb),需要使用 rakedb:test:clone_结构 我们的模式使用uuid(uuidgem)和redhillonrails(RHoR)nicefk插件。不幸的是,FKs需要的PK只能在迁移中使用EXECUTES添加
众所周知,这些执行不会进入schema.rb;然而,很难找到db的rake替代方案:test:为无法使用schema.rb的应用程序做好准备。只是Rails 3(目前为beta 4)上的更新-Christian的解决方案仍然是正确的,唯一正确的地方是在
config/application.rb中,在应用程序
类的范围内,该类应在以Rails项目命名的模块中定义。以下monkeypatch解决了模式转储程序(Rails 3.2)的全文索引问题和DB引擎选项。您可以将其放入config/initializers/
(例如schema\u dumper\u monkeypatch.rb
):
模块活动记录
类SchemaDumper
def表(表,流)
columns=@connection.columns(表)
开始
tbl=StringIO.new
#第一个转储主键列
如果@connection.response_to?(:pk_和_sequence_for)
pk,u=@connection.pk_和_序列(表)
elsif@connection.response_to?(:主键)
pk=@connection.primary_键(表)
结束
tbl.print“创建_表#{删除_前缀和_后缀(表).inspect}”
如果columns.detect{| c | c.name==pk}
如果pk!='身份证
tbl.print%Q(,:主键=>“{pk}”)
结束
其他的
tbl.print“,:id=>false”
结束
tbl.print“,:force=>true”
#添加表引擎
res=@connection.execute“显示类似于“#{TABLE}”的表状态”
engine=res.first[res.fields.index(“引擎”)]救援无
tbl.print“,:options=>'ENGINE={ENGINE}'”如果是ENGINE
res=nil#释放结果
tbl.puts“do | t |”
#然后转储所有非主键列
column_specs=columns.map do | column|
如果@types[column.type].nil,则引发标准错误“#{column.name}”列的未知类型“#{column.sql_type}”?
如果column.name==pk,则下一步
spec={}
spec[:name]=column.name.inspect
#AR有一个将零小数作为整数处理的优化。这
#代码确保转储程序仍将列转储为十进制。
spec[:type]=如果column.type==:整数和[/^numeric/,/^decimal/],是否有?{| e | e.match(column.sql_type)}
“十进制”
其他的
column.type.to_
结束
规格[:限制]=column.limit.inspect如果column.limit!=@类型[列.类型][:限制]&规格[:类型]!='十进制'
规格[:精度]=column.precision.inspect如果column.precision
规格[:比例]=column.scale.inspect如果column.scale
spec[:null]=“false”,除非column.null
spec[:default]=默认字符串(column.default),如果column?
(spec.keys-[:name,:type])。每个{k{spec[k]。插入(0,“{k.inspect}=>”)
规格
紧凑型
#查找此表中使用的所有迁移键
keys=[:name,:limit,:precision,:scale,:default,:null]&列_specs.map{| k | k.keys}.flatten
#根据以上键计算出每列的长度
长度=键。映射{键|列|规范。映射{规范|规范[key]?规范[key]。长度+2:0}.max}
#我们将使用标准化列宽对值进行冲刺的字符串
format_string=length.map{len}“%-{len}s}
#查找“type”列的最大长度,它是特殊的
type_length=column_specs.map{| column | column[:type].length}.max
#将列类型定义添加到格式字符串中
格式_string.unshift“t.%-#{type_length}s”
格式字符串*=“”
列规格每个do | colspec|
values=keys.zip(长度).map{| key,len | colspec.key?(key)?colspec[key]+,:“”*
config.active_record.schema_format = :sql
rake db:structure:dump
module ActiveRecord
class SchemaDumper
def table(table, stream)
columns = @connection.columns(table)
begin
tbl = StringIO.new
# first dump primary key column
if @connection.respond_to?(:pk_and_sequence_for)
pk, _ = @connection.pk_and_sequence_for(table)
elsif @connection.respond_to?(:primary_key)
pk = @connection.primary_key(table)
end
tbl.print " create_table #{remove_prefix_and_suffix(table).inspect}"
if columns.detect { |c| c.name == pk }
if pk != 'id'
tbl.print %Q(, :primary_key => "#{pk}")
end
else
tbl.print ", :id => false"
end
tbl.print ", :force => true"
# Add table engine
res = @connection.execute "SHOW TABLE STATUS LIKE '#{table}'"
engine = res.first[res.fields.index("Engine")] rescue nil
tbl.print ", :options => 'ENGINE=#{engine}'" if engine
res = nil # Free the result
tbl.puts " do |t|"
# then dump all non-primary key columns
column_specs = columns.map do |column|
raise StandardError, "Unknown type '#{column.sql_type}' for column '#{column.name}'" if @types[column.type].nil?
next if column.name == pk
spec = {}
spec[:name] = column.name.inspect
# AR has an optimization which handles zero-scale decimals as integers. This
# code ensures that the dumper still dumps the column as a decimal.
spec[:type] = if column.type == :integer && [/^numeric/, /^decimal/].any? { |e| e.match(column.sql_type) }
'decimal'
else
column.type.to_s
end
spec[:limit] = column.limit.inspect if column.limit != @types[column.type][:limit] && spec[:type] != 'decimal'
spec[:precision] = column.precision.inspect if column.precision
spec[:scale] = column.scale.inspect if column.scale
spec[:null] = 'false' unless column.null
spec[:default] = default_string(column.default) if column.has_default?
(spec.keys - [:name, :type]).each{ |k| spec[k].insert(0, "#{k.inspect} => ")}
spec
end.compact
# find all migration keys used in this table
keys = [:name, :limit, :precision, :scale, :default, :null] & column_specs.map{ |k| k.keys }.flatten
# figure out the lengths for each column based on above keys
lengths = keys.map{ |key| column_specs.map{ |spec| spec[key] ? spec[key].length + 2 : 0 }.max }
# the string we're going to sprintf our values against, with standardized column widths
format_string = lengths.map{ |len| "%-#{len}s" }
# find the max length for the 'type' column, which is special
type_length = column_specs.map{ |column| column[:type].length }.max
# add column type definition to our format string
format_string.unshift " t.%-#{type_length}s "
format_string *= ''
column_specs.each do |colspec|
values = keys.zip(lengths).map{ |key, len| colspec.key?(key) ? colspec[key] + ", " : " " * len }
values.unshift colspec[:type]
tbl.print((format_string % values).gsub(/,\s*$/, ''))
tbl.puts
end
tbl.puts " end"
tbl.puts
indexes(table, tbl)
tbl.rewind
stream.print tbl.read
rescue => e
stream.puts "# Could not dump table #{table.inspect} because of following #{e.class}"
stream.puts "# #{e.message}"
stream.puts
end
stream
end
def indexes(table, stream)
if (indexes = @connection.indexes(table)).any?
add_index_statements = indexes.map do |index|
if index.name =~ /fulltext/i
" execute \"CREATE FULLTEXT INDEX #{index.name} ON #{index.table} (#{index.columns.join(',')})\""
elsif index.name =~ /spatial/i
" execute \"CREATE SPATIAL INDEX #{index.name} ON #{index.table} (#{index.columns.join(',')})\""
else
statement_parts = [
('add_index ' + remove_prefix_and_suffix(index.table).inspect),
index.columns.inspect,
(':name => ' + index.name.inspect),
]
statement_parts << ':unique => true' if index.unique
index_lengths = (index.lengths || []).compact
statement_parts << (':length => ' + Hash[index.columns.zip(index.lengths)].inspect) unless index_lengths.empty?
index_orders = (index.orders || {})
statement_parts << (':order => ' + index.orders.inspect) unless index_orders.empty?
' ' + statement_parts.join(', ')
end
end
stream.puts add_index_statements.sort.join("\n")
stream.puts
end
end
end
end