它被称为heredoc,与迁移,SQL或其他任何特定内容无关:
[当我在http://guides.rubyonrails.org/active_record_migrations.html中在线引用active_record_migrations时
在以下代码段中:
class ExampleMigration < ActiveRecord::Migration[5.0] def up create_table :distributors do |t| t.string :zipcode end # add a CHECK constraint execute <<-SQL ALTER TABLE distributors ADD CONSTRAINT zipchk CHECK (char_length(zipcode) = 5); SQL add_column :users, :home_page_url, :string rename_column :users, :email, :email_address end def down rename_column :users, :email_address, :email remove_column :users, :home_page_url execute <<-SQL ALTER TABLE distributors DROP CONSTRAINT zipchk SQL drop_table :distributors end end
以下陈述是什么意思?
execute <<-SQL
ALTER TABLE distributors
ADD CONSTRAINT zipchk
CHECK (char_length(zipcode) = 5);
SQL
使用rails db:migrate
运行此迁移,出现错误:
SQLite3::SQLException: near "CONSTRAINT": syntax error: ALTER TABLE distributors
ADD CONSTRAINT zipchk
CHECK (char_length(zipcode) = 5) NO INHERIT;
有关更多详细信息,请参见3.9 Using reversible。>>
[当我在http://guides.rubyonrails.org/active_record_migrations.html中在线引用active_record_migrations时,在以下代码段中:类ExampleMigration
它被称为heredoc,与迁移,SQL或其他任何特定内容无关:
[如果您要书写大量文本,则可以使用“此处文档”或“ heredoc”:
expected_result = <<HEREDOC This would contain specially formatted text. That might span many lines HEREDOC
heredoc从<< HEREDOC之后的行开始,并以下一行以HEREDOC开头。结果包括结尾换行符。
您可以将任何标识符与heredoc一起使用,但大写通常使用标识符。
如果在<
expected_result = <<-INDENTED_HEREDOC This would contain specially formatted text. That might span many lines INDENTED_HEREDOC
请注意,虽然结束标识符可以缩进,但内容始终被视为左对齐。如果您缩进内容那些空格将出现在输出中。
由于ActiveRecord::ConnectionAdapters::DatabaseStatements#
execute
将字符串作为参数,因此您正在传递此字符串,格式正确。
此语法用于以sql方式创建迁移,而不是遵循rails active record方式。
优点:它提供了对SQL操作的更多控制,添加了索引,约束等。>
语法:
execute
execute <<-EOSQL
your_sql_here
EOSQL