播种模型不适用于在模型中验证用户

时间:2015-07-25 16:24:05

标签: ruby-on-rails seeding

我的种子看起来像:

seeds.rb

seed_file = File.join(Rails.root, 'db', 'seed.yml')
config = YAML::load_file(seed_file)
Article.create(config["articles"])
User::HABTM_Articles.create(config["articles_users"])

seed.yml

articles:
  - status: 0
    title: First article
    body: Some awesome text

articles_users:
  - article_id: 1
    user_id: 1

我制作rake db:drop && rake db:create && rake db:migrate

然后运行rake db:seed --trace并获得输出:

** Invoke db:seed (first_time)
** Execute db:seed
** Invoke db:abort_if_pending_migrations (first_time)
** Invoke environment (first_time)
** Execute environment
** Execute db:abort_if_pending_migrations

我的Article表格为空,但Article::HABTM_Users为种子。

我发现问题出在Article模型中:

article.rb

class Article < ActiveRecord::Base
  has_and_belongs_to_many :users
  validates :title, presence: true, uniqueness: true
  validates :body, presence: true
  validates :users, presence: true #OK when remove this line
  enum status: [:publ, :priv]
end

删除validates :users, presence: true播种时效果正常。 如何使用该用户状态验证进行播种?

1 个答案:

答案 0 :(得分:0)

问题是,在您创建文章时,它没有用户。我知道您的种子文件将用户列为非常接下来的事情,但ActiveRecord并不耐心验证!因此,您需要做的是在创建文章的同时创建ArticleUsers,您可以通过以下几种方式完成:

  • article_users定义向上推入articles定义:

    articles:
      - status: 0
        title: First article
        body: Some awesome text
        user_ids: [ 1 ]
    

    我做了一些测试,这实际上应该有效:

    irb(main):006:0> Thing.create(name: "thing1", user_ids: [ 1 ] ).users
      User Load (3.1ms)  SELECT  "users".* FROM "users" WHERE "users"."id" = $1 LIMIT 1  [["id", 1]]
      SQL (1.4ms)  INSERT INTO "things" ("name", "created_at", "updated_at") VALUES ($1, $2, $3) RETURNING "id"  [["name", "thing1"], ["created_at", "2015-07-25 16:38:47.717614"], ["updated_at", "2015-07-25 16:38:47.717614"]]
      SQL (0.5ms)  INSERT INTO "things_users" ("user_id", "thing_id") VALUES ($1, $2) RETURNING "id"  [["user_id", 1], ["thing_id", 2]]
    => #<ActiveRecord::Associations::CollectionProxy [#<User id: 1, name: "Bob", age: nil, created_at: "2015-07-25 16:37:13", updated_at: "2015-07-25 16:37:13">]>
    
  • 使用factories,它允许您表达更优雅地生成测试对象的方法,更健壮的fixture solution,或者只是将种子文件转换为知道如何使用的Ruby脚本正确地建立种子。