2016-11-09 107 views
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 

回答

0

這裏有一個快速和骯髒的例子:

require 'active_record' 

ActiveRecord::Base.establish_connection(
    adapter: 'sqlite3', 
    database: 'test.db' 
) 

unless ActiveRecord::Base.connection.table_exists?(:rows) 
    ActiveRecord::Base.connection.create_table :rows do |t| 
    t.string :status_id 
    t.string :name 
    end 
end 

class Row < ActiveRecord::Base 
    after_initialize :set_default_values, unless: :persisted? 

    DEFAULT_STATUS = 5 

    def set_default_values 
    self.status_id = DEFAULT_STATUS if self.status_id.nil? 
    end 

end 

s1 = Row.new(name: "No status") 
s2 = Row.new(name: "Has status", status_id: 1) 

[s1,s2].each do |s| 
    puts "Name: #{s.name}, Status: #{s.status_id}" 
    puts 
end 

輸出:

Name: No status, Status: 5 

Name: Has status, Status: 1 

[Finished in 0.349s] 
+0

哦,我倒並不認爲我喜歡這個解決方案....任何其他想法? – MaciekR

+0

@MaciekR這與您提到的解決方案相同,只需要self.status_id = DEFAULT_STATUS if self.status_id.nil?行(當然還有DEFAULT_STATUS常量)。 –

+0

它不工作(缺少status_id參數) - 在我的模型中。我做了什麼(它工作,但我不知道這是最好的解決方案):我已經添加了行[「status_id」] = DEFAULT_STATUS如果row [「status_id」] ==我的self.import(文件)方法 – MaciekR