我想從我的控制器中分離出一些邏輯,但無法按照我想要的方式工作。我有我的一個功能,需要一個CSV文件,並進入各行到我WeighIns
表:Rails 4:單獨的模型和控制器功能與驗證
# 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:富」一個有用的錯誤
感謝您的詳細回覆,我肯定會採取這些措施。 –