【发布时间】:2016-09-01 14:02:29
【问题描述】:
我试图从我的控制器中分离出一些逻辑,但无法让它按照我想要的方式工作。我的控制器中有一个函数,它接受一个 CSV 文件并将每一行输入到我的 WeighIns 表中:
# Controller (WeighIn belongs_to User)
def bulk_upload_weigh_ins
import = WeighIn.import(params[:file])
redirect_to import_weigh_ins_path, notice: "Weigh Ins Imported Successfully!"
end
然后我的模型中有 CSV 解析功能
# WeighIn model
def self.import(file)
CSV.foreach(file.path, headers: true) do |row|
hashed_row = row.to_hash
# VALIDATE HERE
WeighIn.create hashed_row
end
end
但在 WeighIns 表中创建条目之前,我想确保哈希中有一个属性对应的用户,即User.find_by(scale_id: hashed_row["scale_id"]) != nil 其中scale_id 是我的User 上的行和列的一部分表。
我如何验证这一点并返回一个有用的错误,告诉我“没有用户使用 scale_id: Foo”
【问题讨论】:
标签: ruby-on-rails validation csv model-view-controller