【问题标题】:What does this code do? I do not understand the syntax这段代码有什么作用?我不明白语法
【发布时间】:2014-06-12 16:54:58
【问题描述】:

我正在使用一个月的 Rails,但我对以下代码行感到困惑

rails generate migration add_user_id_to_pins user_id:integer:index

代码在db内的migrate文件夹中生成这个文件:

class AddUserIdToPins < ActiveRecord::Migration
  def change
    add_column :pins, :user_id, :integer
    add_column :pins, :index
  end
end

我不小心输入了

rails generate migration add_user_id_to_pins user_id:integer index:integer

只是因为我假设语法是“变量名”:“变量名的类型”

我的命令生成了以下迁移文件:

class AddUserIdToPins < ActiveRecord::Migration
  def change
    add_column :pins, :user_id, :integer
    add_column :pins, :index, :integer
  end
end

谁能解释一下语法,以及为什么我的代码的两行都有符号整数,而不是第一个命令生成的代码的第一行,并解释继续使用我的代码的含义 vs . 例子。

【问题讨论】:

    标签: ruby-on-rails ruby database-migration


    【解决方案1】:

    rails 生成迁移 add_user_id_to_pins user_id:integer:index

    这表示您有 PIN 模型,并且您希望将名为 user_id 的额外属性添加到 pin。

    我认为您在 pin 和用户之间有关系。喜欢 要么

    user has_many pins
    pin belongs_to user
    

    user has_one pin
    pin belongs_to user
    

    运行迁移的正确命令是

    rails g 迁移 add_user_id_to_pins user_id:integer

    user_id : field name
    Integer : Type that you assigned to user_id.
    

    只存储用户的 id。

    def change
      add_column :pins, :user_id, :integer
    end
    

    这是您可以在迁移文件中看到的内容。

    您添加索引的方式错误。 就像您可以手动添加索引一样。生成迁移文件后转到该迁移并添加

      add_index :pins, :user_id
    

    对于 ActiveRecord 迁移:http://guides.rubyonrails.org/migrations.html 对于 Index In rails,请参考:https://tomafro.net/2009/08/using-indexes-in-rails-index-your-associations

    希望您能了解什么是迁移以及什么/为什么要索引。

    【讨论】:

      【解决方案2】:

      再次检查您的迁移文件。第二行应该是 add_index 而不是 add_coumn。

      来自doc

      如果您想在新列上添加索引,您也可以这样做:

      $ rails generate migration AddPartNumberToProducts part_number:string:index
      

      会生成

      class AddPartNumberToProducts < ActiveRecord::Migration
        def change
          add_column :products, :part_number, :string
          add_index :products, :part_number
        end
      end
      

      【讨论】:

        猜你喜欢
        • 2023-04-01
        • 2014-04-11
        • 2012-05-25
        • 2010-12-14
        • 1970-01-01
        • 2022-06-10
        • 2012-09-01
        • 2020-03-02
        • 2012-11-17
        相关资源
        最近更新 更多