find_or_create方法

时间:2014-04-13 09:47:45

标签: ruby-on-rails csv methods ruby-on-rails-4 find

我有一个简单的CSV导入方法:

  def import
    Player.import(params[:file])
    redirect_to players_path, notice: "Players Imported successfully"
  end
  def self.import(file)
    SmarterCSV.process(file.path) do |chunk|
      chunk.each do |h|
        h[:gr_name] = CGI::unescape(h[:gr_name]).force_encoding('UTF-8')
      end
      # Player.create(chunk.first) 
      # Find if player already exists, then update attributes else create new Player
    end
  end

我检查的变量是" gr_id ",但我无法正确实施。

基本上我需要像

这样的东西
player = Player.find_by_id(row["gr_id"]) || new
Player.create(chunk.first) 

我缺少什么?

2 个答案:

答案 0 :(得分:0)

假设gr_id等于玩家ID,您可以使用以下内容:

Player.find_or_create_by(id: row['gr_id'])

Rails 4中的活动记录查找器示例:http://rails4guides.com/articles/rails-4-activerecord-finders

答案 1 :(得分:0)

def self.import(file)
    CSV.foreach(file.path, headers: true) do |row|
       Player.find_or_create_by(name: row['name'], status: row['status']
      end
      # Player.create(chunk.first) 
      # Find if player already exists, then update attributes else create new Player
    end
  end

这假设玩家具有属性名称和状态,并且CSV文件中的标题是如此命名的。