【问题标题】:Getting undefined method `belongs_to' for #<ActiveRecord::Migration: Error获取#<ActiveRecord::Migration: 错误的未定义方法`belongs_to'
【发布时间】:2016-04-04 18:29:52
【问题描述】:

我正在构建一个短信服务,其中有许多消息与单个用户相关联。我希望通过 from_number 将消息索引到用户表。以下是我所做的,但我不断收到方法错误。

我定义了以下两个模型:

1) 消息.rb

class Message < ActiveRecord::Base
   belongs_to :user
end

2) 用户.rb

class User < ActiveRecord::Base
    has_many :messages
end

以下是我尝试通过 rake db:migrate 运行的迁移文件:

class UsersMessages < ActiveRecord::Migration

  def change
    create_table :users do |t|
      t.string :user_name
      t.string :from_number
      t.timestamps null: false
    end

    create_table :messages do |t|
      t.belongs_to :user, index: true
      t.string :message_body
      t.string :from_number
      t.timestamps null: false
    end

    add_index :users, :from_number, :unique => true
  end
end

我不断收到以下错误:

-- belongs_to(:user)
-- belongs_to(:user)
rake aborted!
NoMethodError: undefined method `belongs_to' for #<ActiveRecord::Migration:0x007ff453826f50>

我在模型中定义了 has_many 和 belongs_to 关联,但这里按照第 2.1 节:http://guides.rubyonrails.org/association_basics.html

我还将“t.belongs_to :customer, index: true”行添加到迁移文件中。

感谢您的帮助!!

【问题讨论】:

  • 您使用的是什么版本的导轨?请运行rails -v 并更新您的答案。 belongs_to in migrations 是在更高版本的 Rails 中添加的,因此您可能正在运行 Rails 3。
  • t.belongs_to :customer, index: true 为什么是:customer
  • 你使用的是哪个版本的 rails @philip-cortes 只是好奇?

标签: ruby-on-rails activerecord has-many belongs-to


【解决方案1】:

尝试在您的迁移中使用t.references :user, index: true..

【讨论】:

【解决方案2】:

您在消息表中缺少user_id

运行 rake db:drop 然后从消息迁移中删除这一行。

t.belongs_to :user, index: true

在命令行中运行:

rails g migration add_user_id_to_messages user_id:interger

rake db:migrate 

【讨论】:

  • 这不能回答 OP 问题。 belongs_to 正在迁移中,rails 使用它为您创建 user_id。
  • @PhilipCortes 只是为了好玩,你能评论belongs_to :user 行并重新启动服务器让我们看看,仍然有同样的问题。
【解决方案3】:

Rails 4 中添加了用于迁移的 belongs_to 语法。您使用的是早期版本吗?

在任何情况下,您都可以简单地自己添加列和索引:

t.integer :user_id, index: true

【讨论】:

    猜你喜欢
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    相关资源
    最近更新 更多