Ruby on rails 问题ActiveRecord::关联

Ruby on rails 问题ActiveRecord::关联,ruby-on-rails,ruby,activerecord,ruby-on-rails-4,devise,Ruby On Rails,Ruby,Activerecord,Ruby On Rails 4,Devise,我用的是宝石“设计”里面的模型,我把它叫做“中心”,我创建了一个模型“书”然后判断 rails g model Book title:string author:string description:text standard_number:integer pages:integer publisher:string year_published:integer 那么对于协会,我已经这样做了 models/center.rb class Center < ActiveRecord::Ba

我用的是宝石“设计”里面的模型,我把它叫做“中心”,我创建了一个模型“书”然后判断

rails g model Book title:string author:string description:text standard_number:integer pages:integer publisher:string year_published:integer
那么对于协会,我已经这样做了

models/center.rb

class Center < ActiveRecord::Base
  has_many :books
  devise :database_authenticatable, :recoverable, :rememberable, :trackable, :validatable
  # :confirmable, :lockable, :timeoutable, :registerable, :omniauthable
end
课程中心
models/book.rb

class Book < ActiveRecord::Base
  belongs_to :center
end
classbook
我的想法是,一个中心(图书馆)出版可以买到的书


错误:

您的图书表中没有中心id。 如果要通过关联调用
书籍
,则子模型中必须有一个参考键(外键)

子元素始终具有
父元素id
。没有这个,你就找不到父/子

当你创建一本书的时候。然后尝试将其添加到关联中

@center = Center.find(params[:id])
@book = @center.books.create(book_params)

这样rails会自动更新书籍中的中心id。

你有一个
有很多
所以你想要
a=center。首先
然后
a.books
不,一定是因为他们相信模型中的“中心id”?错误:很好,我错过了那一点。