【问题标题】:Rails CSV IMPORT first_or_createRails CSV 导入 first_or_create
【发布时间】:2020-02-14 00:57:18
【问题描述】:

您好,我有一个非常基本的 csv 导入器,用户可以使用它来导入项目。项目属于_to a :part_number

当用户导入我要添加的第一个或创建到导入的项目时,以通过其名称查找或创建零件编号。 我想要的 CSV 文件列

name, part_number.name

架构

 create_table "items", force: :cascade do |t|
        t.bigint "project_id"
        t.string "name"
        t.datetime "created_at", null: false
        t.datetime "updated_at", null: false
        t.integer "status", default: 0
        t.bigint "part_number_id"
        t.index ["part_number_id"], name: "index_items_on_part_number_id"
        t.index ["project_id"], name: "index_items_on_project_id"
      end

create_table "part_numbers", force: :cascade do |t|
    t.string "name"
    t.datetime "created_at", null: false
    t.datetime "updated_at", null: false
  end

app/models/item.rb

    class Item < ApplicationRecord
          belongs_to :project
          belongs_to :part_number

          def self.import(file)
            CSV.foreach(file.path, headers: true, header_converters: :symbol) do |row|
              Item.create! row.to_hash
            end
          end
end

app/models/part_number.rb

class PartNumber < ApplicationRecord
    has_many :items
end

app/controllers/projects/items_controller.rb

类项目::ItemsController

  # GET /items/new
  def new
    @project = Project.find(params[:project_id])
    @item = Item.new
  end

  def index
    @project = Project.find(params[:project_id])
    @items = @project.items.all
    respond_to do |format|
      format.html
      format.csv { send_data @items.to_csv }
    end
  end
  # GET /items/1/edit
  def edit
  end

  # POST /items
  # POST /items.json
  def create
    @project = Project.find(params[:project_id])
    @item = Item.new(item_params)
    @item.project_id = @project.id
    respond_to do |format|
      if @item.save
        format.html { redirect_to @item.project, notice: 'Item was successfully created.' }
        format.json { render :show, status: :created, location: @item.project }
      else
        format.html { render :new }
        format.json { render json: @item.project.errors, status: :unprocessable_entity }
      end
    end
  end

  # PATCH/PUT /items/1
  # PATCH/PUT /items/1.json
  def update
    @item = Item.find(params[:id])
    @project = Project.find(params[:project_id])
    respond_to do |format|
      if @item.update(item_params)
        format.html { redirect_to @item.project, notice: 'Item was successfully updated.' }
        format.json { render :show, status: :ok, location: @item.project }
      else
        format.html { render :edit }
        format.json { render json: @item.project.errors, status: :unprocessable_entity }
      end
    end
  end

  # DELETE /items/1
  # DELETE /items/1.json
  def destroy
    @item = Item.find(params[:id])
    @project = Project.find(params[:project_id])
    title = @item.model
    if @item.destroy
      flash[:notice] = "One \'#{title}' was successfully destroyed."
      redirect_to @project 
    else
      flash[:notice] = "Error Yo"
      render :show
    end
  end

  def import
    @project = Project.find(params[:project_id])
    @project.items.import(params[:file])
    redirect_to projects_path(@project), notice: "Sucessfully Imported Items!"
   end

  private
    # Use callbacks to share common setup or constraints between actions.

    # Never trust parameters from the scary internet, only allow the white list through.
    def item_params
      params.require(:item).permit(:model, :project_id, :name, :search, part_number: [:id, :name])
    end
end

【问题讨论】:

  • 您希望哪个字段成为标识符来决定您应该创建记录还是只查找记录?还是应该 CSV 中的每一列都匹配记录的每个属性?
  • @Mark the name of the part_number so part_number.name。谢谢一堆。所以每一行可以有不同的part_number.name
  • @Mark 忘记了现在添加的控制器...不确定我的参数是否与 part_number 相关:[:id, :name]

标签: ruby-on-rails csv import import-csv


【解决方案1】:

如果您的名称参数作为每行(行 [0])的第一列出现,那么我认为这样的事情应该可以工作:

class Item < ApplicationRecord
  belongs_to :project
  belongs_to :part_number

  def self.import(file)
    CSV.foreach(file.path, headers: true, header_converters: :symbol) do |row|
      Item.where(name: row[0]).find_or_create_by do |item|
        item.update_attributes(row.to_hash)
      end
    end
  end
end

在导入 CSV 时使用 find_or_create_by 的不错的教程:

https://www.driftingruby.com/episodes/importing-and-exporting-csv-data

【讨论】:

  • 谢谢@mark 请问PartNumber是在哪里创建的?
  • 我更改为以下内容并使其正常工作 def self.import(file) CSV.foreach(file.path, headers: true) do |row| item_hash = row.to_hash part_number = PartNumber.find_or_create_by!(name: item_hash['part']) item = Item.create!(name: item_hash['name'], part_number_id: part_number.id) end end
  • Soz 参加了会议 - 很高兴你到了那里 :)
猜你喜欢
  • 1970-01-01
  • 1970-01-01
  • 2017-01-08
  • 1970-01-01
  • 1970-01-01
  • 1970-01-01
  • 1970-01-01
  • 1970-01-01
  • 1970-01-01
相关资源
最近更新 更多