1
add_index :section_edits, ['admin_user_id', 'section_id' ]

add_index :sections, [:name, :page_id]

I know the variables are different, but my question is regarding how to pass the variables (i.e. :page_id vs 'page_id'). Does it makes a difference? Which one is better?

I have noted that when I use :name it is already defined before I pass the variable, but if I use 'section_id' , following a tutorial, this variable was not previously defined.

Here is some sample code:

class CreateSections < ActiveRecord::Migration
  def change
    create_table :sections do |t|

      t.references :page
      t.string :name
      t.string :content_type
      t.integer :position
      t.boolean :visible
      t.text :content

      t.timestamps
    end
    add_index :sections, [:name, :page_id]
  end
end   

class CreateSectionEdits < ActiveRecord::Migration
  def change
    create_table :section_edits do |t|
      t.references :admin_user
      t.references :section

      t.timestamps
    end

    add_index :section_edits, ['admin_user_id', 'section_id' ]
  end
end

Thank you!

4

1 回答 1

1

add_index的文档将 column_name(有问题的参数)描述为符号或符号数组,因此这些是要使用的正确(因此更好)类型。其他参数类型产生相同结果的事实应被视为不可指望的实现副作用。(您可以通过遵循源代码了解为什么字符串目前与符号一样有效。)

我不确定你之前定义的 :name 和 'section_id' 变量是什么意思,因为 :name 是一个符号,而 'section_id' 是一个字符串文字,两者都不能用作变量。如果您指的是变量namesection_id,它们与相应的符号和字符串无关,因此它们是否已定义或未定义是无关紧要的。

并不是要对上述答案挑剔,但您是在询问具体情况,而我只是想弄清楚。:-)

于 2013-05-05T20:02:59.420 回答