【问题标题】:Import and Create Records from CSV从 CSV 导入和创建记录
【发布时间】:2016-04-10 03:30:59
【问题描述】:

我正在尝试通过 CSV 文件上传在 配对 表中创建记录。给出的文件将采用这种格式

supervisor,student,project_title
Bob,Alice,Web Site
Bob,Charlie,Web Application

问题是配对表不包含主管或学生的姓名,而是他们的 ID,因此有必要在 User 表中搜索这些给定名称并选择他们的 ID,然后使用这些 ID 创建配对并给定的项目标题。

下面的代码给了我太多重定向错误,并在配对表中插入了一条空记录。

配对.rb

def self.import(file)

    CSV.foreach(file.path, headers: true) do |row|

      supervisorName = row[0]
      studentName = row[1]
      title = row [2]

      supervisorID = User.select(:id).where(name: supervisorName)
      studentID = User.select(:id).where(name: studentName)

      pair = Pairing.new
      pair.supervisor_id = supervisorID
      pair.student_id = studentID
      pair.project_title = title
      pair.save

    end
end

Pairings_controller.rb

  def new
    @pairing = Pairing.new
  end

  def create
    @pairing = Pairing.new(pairing_params)
    if @pairing.save
      redirect_to pairings_path, :notice => "Pairing Successful!"
    else 
      redirect_to pairings_path, :notice => "Pairing Failed!"
    end
  end

  def import
    Pairing.import(params[:file])
    redirect_to pairings_path, :notice => "Pairs Imported"
  end

【问题讨论】:

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


    【解决方案1】:

    语句User.select(:id).where(name: supervisorName) 不会像您期望的那样返回整数值。考虑改用User.find_by(name: supervisorName).id

    对于过多的重定向,请确保与您的pairings_path 匹配的操作不会重定向回自身或其他可能产生循环重定向的操作。

    【讨论】:

    • 将 select 语句更改为 find_by 有效,似乎也重定向了与之相关的位置。谢谢!
    猜你喜欢
    • 2023-03-19
    • 1970-01-01
    • 1970-01-01
    • 2018-06-10
    • 2016-09-16
    • 2012-05-25
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    相关资源
    最近更新 更多