0

Rails 3. 这是我的代码:

class AddForAutocompleteInShops < ActiveRecord::Migration
  def up
    add_column :shops, :for_autocomplete, :string
  end

  Shop.reset_column_information

  shops = Shop.all

  shops.each do |shop|
    shop.for_autocomplete = %(#{shop.name} #{shop.formatted_address})
    shop.save
  end

  def down
    remove_column :shops, :for_autocomplete
  end
end

出现错误信息:

rake aborted!
An error has occurred, all later migrations canceled:

undefined method `for_autocomplete=' for #<Shop:0x007fba66be7af8>
/Users/abc/Sites/test/db/migrate/20130219121256_add_for_autocomplete_in_shops.rb:11:in `block in <class:AddForAutocompleteInShops>'
/Users/abc/Sites/test/db/migrate/20130219121256_add_for_autocomplete_in_shops.rb:10:in `each'
/Users/abc/Sites/test/db/migrate/20130219121256_add_for_autocomplete_in_shops.rb:10:in `<class:AddForAutocompleteInShops>'
/Users/abc/Sites/test/db/migrate/20130219121256_add_for_autocomplete_in_shops.rb:1:in `<top (required)>'
Tasks: TOP => db:migrate
(See full trace by running task with --trace)

我的代码有什么问题?我在 Rails 控制台中测试它工作正常。

谢谢。

4

2 回答 2

2

您的代码应该是upordown方法的一部分 - 而不是在迁移类的中间。

于 2013-02-19T12:38:09.470 回答
1
    class AddForAutocompleteInShops < ActiveRecord::Migration
      def up

        add_column :shops, :for_autocomplete, :string

        Shop.reset_column_information

        shops = Shop.all

        shops.each do |shop|
          shop.for_autocomplete = %(#{shop.name} #{shop.formatted_address})
          shop.save
        end
      end



      def down
        remove_column :shops, :for_autocomplete
      end
    end

Try this.
于 2013-02-19T12:45:26.177 回答