[英]Getting undefined method `belongs_to' for #<ActiveRecord::Migration: Error
我正在建立一個短信服務,其中有許多消息綁定到一個用戶。 我希望消息通過它們的from_number索引到用戶表。 以下是我已經完成的工作,但是我不斷遇到方法錯誤。
我定義了以下兩個模型:
1)message.rb
class Message < ActiveRecord::Base
belongs_to :user
end
2)User.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”行添加到遷移文件中。
謝謝您的幫助!!
嘗試在遷移中使用t.references :user, index: true
。
您在“消息”表中缺少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
Rails 4中添加了進行遷移的belongs_to
語法。是否可能使用的是較早版本?
無論如何,您都可以簡單地添加列並自己建立索引:
t.integer :user_id, index: true
聲明:本站的技術帖子網頁,遵循CC BY-SA 4.0協議,如果您需要轉載,請注明本站網址或者原文地址。任何問題請咨詢:yoyou2525@163.com.