【发布时间】: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_toin migrations 是在更高版本的 Rails 中添加的,因此您可能正在运行 Rails 3。 -
t.belongs_to :customer, index: true为什么是:customer? -
你使用的是哪个版本的 rails @philip-cortes 只是好奇?
标签: ruby-on-rails activerecord has-many belongs-to