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控制台中测试它运行正常。
感谢。
答案 0 :(得分:2)
您的代码应该是up
或down
方法的一部分 - 而不是在迁移类的中间。
答案 1 :(得分: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.