Rails 中的"执行 <<-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使用可逆

它被称为heredoc,与迁移、SQL或任何其他特定的东西无关:

如果你写的是一大块文字,你可以使用" here document "或"heredoc":

expected_result = <<HEREDOC
This would contain specially formatted text.
That might span many lines
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的活动记录方式。

优点:它提供了对SQL操作的更多控制,可以添加索引、约束等。

语法:

execute <<-EOSQL your_sql_here EOSQL

class CreateEmployers < ActiveRecord::Migration def up execute <<-EOSQL CREATE TABLE employers (id bigint(20) NOT NULL;designation_id int(11) NOT NULL,salary int(11) DEFAULT NULL);EOSQL结束def下来执行& lt; & lt; -EOSQL删除表 employersEOSQL结束结束

相关内容

最新更新