【问题标题】:Rails: How do I get reference from one .yml files to second .yml fileRails:如何从一个 .yml 文件中获取对第二个 .yml 文件的引用
【发布时间】:2020-09-23 05:19:32
【问题描述】:

我有 2 个模型用户和帐户,我想使用 .yml 文件在其中创建种子数据

用户.rb

class User < ApplicationRecord
  has_one: account
end

和 account.rb

class Account < ApplicationRecord
  belongs_to: user
end

我的 .yml 文件是

config/users.yml

user1: 
  first_name: 'John'
  last_name: 'Doe'
user2: 
  first_name: 'John'
  last_name: 'Wick'

and config/accounts.rb

account1:
  balance: 1000
  slug: 'saving'
account2: 
  balance: 500
  slug: 'marketing'

所以我的问题是如何将 user1 添加到 account1 并将 user2 添加到 account2 等等。 以及如何在种子文件中使用它来创建一些数据。 谢谢:)

【问题讨论】:

  • 您为什么尝试在 yaml 文件中处理您的用户和帐户?为什么不将其存储在数据库中?还是您想将这些数据用作固定装置或种子?你用ruby-on-rails-3标记你的问题,你真的还在使用大约7岁的Rails版本3吗?
  • @spickermann 我想在种子中使用它

标签: ruby-on-rails yaml


【解决方案1】:

Rails 获取种子数据的方法是在 db/seeds.rb 中创建一个 Ruby 文件,如下所示:

user1 = User.create(first_name: 'John', last_name: 'Doe')
user2 = User.create(first_name: 'John', last_name: 'Wick')

Account.create(user: user1, balance: 1000)
Account.create(user: user2, balance: 500)

并使用rails db:seed 运行它

Rails Guides about seed data

【讨论】:

    【解决方案2】:

    我得到了解决方案 首先,您必须根据我们的帐户 slug 在 users.yml 中添加帐户 slug 的引用

    user1: 
      first_name: 'John'
      last_name: 'Doe'
      account_slug: 'saving'
    user2: 
      first_name: 'John'
      last_name: 'Wick'
      account_slug: 'marketing'
    

    所以现在在我的种子文件中,我会将用户的 account_slug 与 account.yml 的 slug 属性进行比较。

    user_seed_file = File.join(Rails.root, 'config', 'users.yml')
    user_config = YAML::load_file(user_seed_file)
    
    account_seed_file = File.join(Rails.root, 'config', 'accounts.yml')
    account_config = YAML::load_file(account_seed_file)
    
    user_config.each do |user_key, user_value|
      user = User.find_or_create_by(user_value.except("account_slug"))
      account_config.each do |account_key, account_value|
        account = user.account.present? ? user.account : user.create_account(account_value) if account_value["slug"] == user_value["product_slug"]
      end
    end
    
    

    它将完全满足我们的需要

    在代码中这一行

    user = User.find_or_create_by(user_value.except("account_slug"))
    

    从 users.yml 文件中获取除 account_slug 之外的所有属性,因为它是一个额外的属性。

    谢谢

    【讨论】:

      猜你喜欢
      • 2012-07-17
      • 2012-01-23
      • 1970-01-01
      • 1970-01-01
      • 2014-03-21
      • 2016-03-25
      • 1970-01-01
      • 2019-05-29
      • 1970-01-01
      相关资源
      最近更新 更多