Ruby on rails Rails:如何从一个.yml文件获取到第二个.yml文件的引用
我有两个模型用户和帐户,我想使用.yml文件在中创建种子数据 user.rbRuby on rails Rails:如何从一个.yml文件获取到第二个.yml文件的引用,ruby-on-rails,yaml,Ruby On Rails,Yaml,我有两个模型用户和帐户,我想使用.yml文件在中创建种子数据 user.rb class User < ApplicationRecord has_one: account end 所以我的问题是如何将user1添加到account1,将user2添加到account2等等。 我如何在种子文件中使用它来创建一些数据。 谢谢:)Rails获取种子数据的方法是在db/seeds.rb中创建一个Ruby文件,如下所示: user1 = User.create(first_name: 'Jo
class User < ApplicationRecord
has_one: account
end
所以我的问题是如何将user1添加到account1,将user2添加到account2等等。
我如何在种子文件中使用它来创建一些数据。
谢谢:)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运行它
参见我得到了解决方案
首先,您必须在users.yml中添加account slug的引用,就像我们的account 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之外的所有属性,因为它是一个额外属性
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
谢谢为什么您要尝试在yaml文件中处理您的用户和帐户?为什么不把它存储在数据库中呢?还是要将这些数据用作装置或种子?你用
ruby-on-rails-3
标记了你的问题,你真的还在使用大约7年前的rails版本3吗?@spickermann我想在seeds中使用它
user = User.find_or_create_by(user_value.except("account_slug"))