gpt4 book ai didi

ruby-on-rails - `execute <<-SQL` 在 Rails 中是什么意思?

转载 作者:数据小太阳 更新时间:2023-10-29 07:15:51 25 4
gpt4 key购买 nike

当我在 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了解更多详情。

最佳答案

它叫做 heredoc与迁移、SQL 或其他任何具体内容无关:

If you are writing a large block of text you may use a “here document” or “heredoc”:

expected_result = <<HEREDOC

This would contain specially formatted text.

That might span many lines
HEREDOC

The heredoc starts on the line following << HEREDOC and ends with the next line that starts with HEREDOC. The result includes the ending newline.

You may use any identifier with a heredoc, but all-uppercase identifiers are typically used.

You may indent the ending identifier if you place a “-” after <<:

  expected_result = <<-INDENTED_HEREDOC
This would contain specially formatted text.

That might span many lines
INDENTED_HEREDOC

Note that the while the closing identifier may be indented, the content is always treated as if it is flush left. If you indent the content those spaces will appear in the output.

ActiveRecord::ConnectionAdapters::DatabaseStatements#execute将一个字符串作为参数,您传递的是这个字符串,格式正确。

关于ruby-on-rails - `execute <<-SQL` 在 Rails 中是什么意思?,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/40394654/

25 4 0
Copyright 2021 - 2024 cfsdn All Rights Reserved 蜀ICP备2022000587号
广告合作:1813099741@qq.com 6ren.com