上傳.csv檔案以及將圖片上傳到我的網頁時出現錯誤:
ImagesController 中的錯誤 NoMethodError#import 未定義的方法 `import' for Image:Class
模型/image.rb
class Image < ApplicationRecord
has_one_attached :avatar
end
def self.import
CSV.foreach(file.path, headers: true) do |row|
Image.create! row.to_hash
end
end
控制器/images_controller.rb
def import
Image.import(params[:file])
redirect_to images_path, notice: "excel import successfully"
end
uj5u.com熱心網友回復:
- 您應該
end從行號中洗掉。3 并將其放在檔案的末尾,即類方法和實體方法應在此處定義在一個類中 - 由于方法
import接受引數,將其定義為import(arg)
下面的代碼段應該可以幫助您更好地理解。
class Image < ApplicationRecord
has_one_attached :avatar
def self.import(file)
CSV.foreach(file.path, headers: true) do |row|
Image.create! ... # required attributes
end
end
end
轉載請註明出處,本文鏈接:https://www.uj5u.com/qukuanlian/416209.html
標籤:
上一篇:Ruby陣列元素
