I have a model called Treating that requires the presence of both a ‘requestor’ and a ‘requestee’. Neither of these attributes are accessible in the Treating model. Here’s the model:
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
I am trying to populate the test database with this rake file, 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
Unless I make :requestor an accessible attribute in the Treating model and follow ‘intro: intro’ with ‘requestee: requestee’ in the ‘requestor.sent_treatings.create!(intro: intro)’ line of my rake file, I will get a Validation error when I run rake db:populate saying that ‘requestee is blank’:
rake aborted!
Validation failed: Requestee can't be blank
Tasks: TOP => db:populate
1) [more imporant] How do I set ‘requestee’ in my rake file without having to make it accessible in the model?
2) I have a hacky approach to declaring the ‘requestee’ variable within my ’50.times.do’ loop: ‘requestee = User.find(rand(1..6))’. What is a better way to declare this similar to how I declare my ‘requestor’ variable in ‘requestors.each do |requestor|’?
Thanks so much!
1 Answer