我有一个名为治疗的模型,需要“请求者”和“被请求者”的存在。在治疗模型中无法访问这些属性。这是模型:
class Treating < ActiveRecord::Base
attr_accessible :intro, :proposed_date, :proposed_location
validates :intro, presence: true, length: { maximum: 190 }
validates :requestor_id, presence: true
validates :requestee_id, presence: true
belongs_to :requestor, class_name: "User"
belongs_to :requestee, class_name: "User"
default_scope order: 'treatings.created_at DESC'
end
我正在尝试使用此rake文件填充测试数据库,sample_data.rake:
namespace :db do
desc "Fill database with sample data"
task populate: :environment do
...
requestors = User.all(limit: 6)
50.times do
intro = Faker::Lorem.sentence(5)
requestors.each do |requestor|
requestee = User.find(rand(1..6))
requestor.sent_treatings.create!(intro: intro)
end
end
end
end
除非我在处理模型中使用:requestor一个可访问的属性,并在我的rake文件的'requestor.sent_treatings.create!(intro:intro)'行中跟随'intro:intro'和'requestee:requestee',当我运行rake db时会得到一个验证错误:填充说'被请求者是空的':
rake aborted!
Validation failed: Requestee can't be blank
Tasks: TOP => db:populate
1)[更重要]如何在我的rake文件中设置'被请求者'而不必在模型中访问它? 2)我有一个hacky方法在'50 .times.do'循环中声明'requestee'变量:'requestee = User.find(rand(1..6))'。什么是更好的方式来声明这与我在'requestors.each do | requestor |'中声明我的'requestor'变量的方式类似?
非常感谢!
答案 0 :(得分:0)
namespace :db do
desc "Fill database with sample data"
task populate: :environment do
...
requestors = User.all(limit: 6)
requestees = User.find((1..6).to_a)
50.times do
intro = Faker::Lorem.sentence(5)
requestors.each do |requestor|
requestee = requestees.sample #random array member, Ruby 1.9+
treating = requestor.sent_treatings.build(intro: intro)
treating.requestee = requestee
treating.save!
end
end
end
end