【发布时间】:2015-09-20 10:10:46
【问题描述】:
感谢这个社区,它已经帮助了我很多。这是我必须向自己发布的第一个问题,它在某种程度上是针对我的项目的。
我是从 MHartls 伟大的 Rails 教程开始的。 有用户和微博的模型,我添加了一个汽车模型,每个用户都可以拥有一辆车(由 car_id 引用)。
在控制台中,我可以创建一个用户和一个微博,并通过声明 post.user = michael 将用户分配给微博,然后它将帖子的 user_id 设置为 michaels id。 我正在尝试对汽车做同样的事情,我可以通过声明 michael.car = somecar 来设置用户 car_id 但即使模型关联看起来完全相同,它也会出错,我什至将 car_id 重新迁移到用户模型作为参考。见下文:
class User < ActiveRecord::Base
has_many :microposts, dependent: :destroy
belongs_to :cars
class Micropost < ActiveRecord::Base
belongs_to :user
belongs_to :car
class Car < ActiveRecord::Base
has_many :microposts, dependent: :destroy
has_many :users
accepts_nested_attributes_for :users
accepts_nested_attributes_for :microposts
这是我对 car_id 的最后一次迁移:
class Addreferencecartousers < ActiveRecord::Migration
def change
add_reference :users, :car
add_foreign_key :users, :cars
end
end
与我为用户/微帖子连接所做的同步。
我有点迷失在哪里寻找为什么这不起作用,有人对我在这里缺少什么有任何提示/指针吗?
【问题讨论】:
标签: ruby-on-rails ruby-on-rails-4 model migration model-associations