【问题标题】:Problems ActiveRecord::Associations问题 ActiveRecord::Associations
【发布时间】:2014-10-07 14:30:28
【问题描述】:

我正在使用gem“Devise”,其中的模型我称之为“Center”,我创建了一个模型“Book”然后判断。

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

我的想法是一个中心(图书馆)出版可用的书籍。

错误:https://gist.github.com/anonymous/de052aefaa63cc7fcf3e

【问题讨论】:

标签: ruby-on-rails ruby activerecord ruby-on-rails-4 devise


【解决方案1】:

您的 books 表中没有 center_id。 如果您想通过关联调用books,您的子模型中必须有一个引用键(外键)。

子元素总是有parent_id。没有这个,你就找不到父母/孩子。

在您创建图书时也是如此。然后尝试使用关联添加它。

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

这样rails会自动更新books中的center_id。

【讨论】:

  • 好地方,我错过了。
猜你喜欢
  • 1970-01-01
  • 2022-12-27
  • 1970-01-01
  • 1970-01-01
  • 2018-03-02
  • 1970-01-01
  • 1970-01-01
  • 1970-01-01
  • 2016-11-18
相关资源
最近更新 更多