【问题标题】:has_many relationship not working in a fixturehas_many 关系在夹具中不起作用
【发布时间】:2014-08-02 09:55:18
【问题描述】:

我的用户模型:

class User < ActiveRecord::Base
  has_many :articles, :dependent => :destroy
end

文章型号:

class Article < ActiveRecord::Base
  belongs_to :user
end

文章夹具:

one:
  url: http://www.google.com/
  title: Sample Title
  user: default

用户夹具:

default:
  email: user@example.com
  name: Test User

在测试用例中尝试Article.first.user 效果很好,但如果我尝试在我的用户夹具中使用以下内容来获得相反的关系:

default:
  email: user@example.com
  name: Test User
  articles: one

我收到以下错误:

ActiveRecord::StatementInvalid: PG::UndefinedColumn: ERROR:  column "articles" of relation "users" does not exist

【问题讨论】:

  • 您不需要articles: one。它应该会自动运行。
  • @SampritiPanda 你能把它放在答案中吗?非常感谢。

标签: ruby-on-rails relationship fixtures


【解决方案1】:

您不需要在 users 夹具中添加另一行来指定文章列表。您需要做的就是在文章夹具中指定用户(为文章设置user_id 列),Rails 使用该外键为用户找出文章。

所以,你的文章夹具应该是:

default:
  email: user@example.com
  name: Test User

【讨论】:

    猜你喜欢
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 2017-01-23
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    相关资源
    最近更新 更多