【问题标题】:Referencing fixtures from the same type in Rails在 Rails 中引用相同类型的固定装置
【发布时间】:2011-01-17 04:43:49
【问题描述】:

在不同模型之间的关联中,可以避免直接使用 this answer 中的夹具名称来设置外键 ID。自引用关联又如何呢,例如在使用acts_as_tree 时?试试这个:

# categories.yml
forsale:
  name: For Sale
  parent_id: nil

books:
  name: Books
  parent: forsale

我收到此错误:

SQLite3::SQLException: table categories has no column named parent: INSERT INTO "categories" ("name", "parent") VALUES ('Books', 'forsale')

有没有什么方法可以在不使用显式 ID 的情况下让一个灯具引用同一类中的另一个灯具?

更新:

polymorphic belongs_to 固定装置的括号之间附加类名也不起作用。这样做:

books:
  name: Books
  parent: forsale (Category)

books 生成一个随机的parent_id,而不是forsale 的ID。

【问题讨论】:

    标签: ruby-on-rails unit-testing fixtures


    【解决方案1】:

    我已经这样做了好几次,但不知道为什么它不适合你。固定装置看起来是正确的(没有多态 (Category))。该关联是否适用于您的应用程序的其余部分?你用的是什么版本的 Rails?你的 Category 模型中应该有这样的东西:

    belongs_to :parent, :class_name => "Category"
    

    如果你只想强制它工作,你可以像这样设置一个明确的parent_id

    books:
      name: Books
      parent_id: <%= Fixtures.identify :forsale %>
    

    但这显然不太理想......

    【讨论】:

    猜你喜欢
    • 1970-01-01
    • 1970-01-01
    • 2016-03-24
    • 1970-01-01
    • 2014-08-24
    • 2010-11-17
    • 1970-01-01
    • 2015-05-22
    • 1970-01-01
    相关资源
    最近更新 更多