0

我有一个名为 Treating 的模型,它需要同时存在“请求者”和“被请求者”。这些属性都不能在处理模型中访问。这是模型:

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:populate 时出现验证错误,说“被请求者为空白”:

rake aborted!
Validation failed: Requestee can't be blank

Tasks: TOP => db:populate

1) [更重要] 如何在我的 rake 文件中设置 'requestee' 而不必使其在模型中可访问?2)我有一个hacky方法来在我的'50.times.do'循环中声明'requestee'变量:'requestee = User.find(rand(1..6))'。有什么更好的方式来声明这个类似于我在“requestors.each do |requestor|”中声明我的“requestor”变量的方式?

非常感谢!

4

1 回答 1

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
于 2012-08-03T14:42:50.867 回答