1
在我的應用程序,用戶可以從一個XLSX文件導入地方:Rails5 /如何設置默認屬性值對進口物品
控制器的地方:
def import
Place.import(params[:file])
respond_to do |format|
format.html { redirect_to admin_places_url, notice: 'Places were successfully imported.' }
format.json { head :no_content }
end
end
根據我的模型 - 每個地方belongs_to的:狀態和
validates :status,
presence: true,
uniqueness: false,
inclusion: {in: Status.all}
我想爲導入的地方設置默認狀態(status_id) - 如果他們沒有。
after_initialize :set_default_values, unless: :persisted?
和
def set_default_values
self.status_id = 2 if # ???
end
我的問題是:如何定義set_default_values方法?
更新:
我的解決方案,它的工作原理:
def self.import(file)
spreadsheet = open_spreadsheet(file)
puts spreadsheet.inspect
header = spreadsheet.row(1)
(2..spreadsheet.last_row).each do |i|
row = Hash[[header, spreadsheet.row(i)].transpose]
place = find_by_id(row["id"]) || new
row["status_id"] = DEFAULT_STATUS if row["status_id"]==nil # NEW
place.attributes = row.to_hash #works for xlsx doesn't work for csv - unknown attributes for Place.
place.save!
end
end
def set_default_values
self.status_id = DEFAULT_STATUS if self.status_id.nil?
end
哦,我倒並不認爲我喜歡這個解決方案....任何其他想法? – MaciekR
@MaciekR這與您提到的解決方案相同,只需要self.status_id = DEFAULT_STATUS if self.status_id.nil?行(當然還有DEFAULT_STATUS常量)。 –
它不工作(缺少status_id參數) - 在我的模型中。我做了什麼(它工作,但我不知道這是最好的解決方案):我已經添加了行[「status_id」] = DEFAULT_STATUS如果row [「status_id」] ==我的self.import(文件)方法 – MaciekR