我有一個函數在我的模型中從CSV文件導入數據,我想驗證應該有任何錯誤。例如,當我上傳文件時,我根據文件中的ID搜索User
。如果沒有User
與該ID,我想redirect_to
一個錯誤的另一頁。Redirect_to模型出錯後
def self.getUser(scale_id)
@user = User.find_by(scale_id: scale_id)
if @user == nil
redirect_to users_path
else
return @user
end
end
def self.bulk_upload_weigh_ins(file)
output = []
errors = []
CSV.foreach(file.path, headers: true,) do |row|
row = row.to_hash
@scale_id = row["scale_id"]
@user = getUser(@scale_id)
row.merge!(user_id: @user_id)
WeighIn.create! row.to_hash
end
end
...而且無論我把什麼路那裏,我得到如下:undefined local variable or method 'users_path' for #<Class:0x007fa06f466998>
即使它是一個有效的路徑。
像這樣重定向有什麼問題嗎?如果是,我該怎麼做?
路徑助手在模型中不可用,除非您特別包含它們。不應特別包括它們;模型應該儘可能的不可知,並且不應該有關於網絡事物的具體知識。另外,遵循Ruby約定並命名方法'get_user'可能是一個好主意......但我會更進一步並說方法命名不正確。你將在你的模型中設置一個類級的實例變量 - 你應該返回一個本地的'user'實例,而不是使用一個類級的實例變量。海事組織不應該擁有自己的方法。 –