Getting undefined method `belongs_to&#39; for #<activerecord::migration: error=""

时间:2016-04-04 18:29:52

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

="" I'm building a texting service, where there are many messages tied to a single user. I'd like for messages to be indexed to the user table via their from_number. Below is what I've done, but I keep getting a method error.

I have the following two models defined:

1) message.rb

class Message < ActiveRecord::Base
   belongs_to :user
end

2) User.rb

class User < ActiveRecord::Base
    has_many :messages
end

The following is the migration file I'm trying to run via 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

I keep getting the following error:

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

I define the has_many and belongs_to associations in the model, but as per Section 2.1 here: http://guides.rubyonrails.org/association_basics.html

I add the "t.belongs_to :customer, index: true" line to the migration file as well.

Thank you for your help!!

3 个答案:

答案 0 :(得分:0)

Try using t.references :user, index: true in your migration..

答案 1 :(得分:0)

You are missing user_id in Messages table.

Run rake db:drop then remove from messages migration this line.

t.belongs_to :user, index: true

Run in command line this:

rails g migration add_user_id_to_messages user_id:interger

and

rake db:migrate 

答案 2 :(得分:0)

在Rails 4中添加了belongs_to迁移语法。您是否可以使用早期版本?

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

t.integer :user_id, index: true