Rails5 /如何为导入的对象设置默认属性值

时间:2016-11-09 23:37:17

标签: ruby-on-rails

在我的应用中,用户可以从xlsx文件中导入地点:

控制器位置:

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:status和

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

1 个答案:

答案 0 :(得分: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]