【问题标题】:find_or_create Methodfind_or_create 方法
【发布时间】:2014-04-13 09:47:44
【问题描述】:

我有一个简单的 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) 

我错过了什么?

【问题讨论】:

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


    【解决方案1】:

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

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

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

    【讨论】:

    • 我试过了,#<0x007fb8a0c59738>
    【解决方案2】:
    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
    

    这是假设 Player 具有属性 name 和 status 并且 CSV 文件中的标题是这样命名的。

    【讨论】:

      猜你喜欢
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      • 2021-07-30
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      相关资源
      最近更新 更多