Rails 如何在 Rails 的下载里面增加用户名

ChileNeverDie · February 23, 2020 · Last by ChileNeverDie replied at February 24, 2020 · 2505 hits

目前在做的项目,我在问题汇总界面加了个下载按钮,但是下载下来的话只有用户 id 没有用户的名字,求问这种情况的话,要做个什么样的 migration 才能把用户名放到下载的 csv 里面去啊

下载的 csv 文件

problem_controller.rb

def index
  @problems = Problem.paginate(page: params[:page])
  time = Time.new.strftime("%Y%m%d%H%M%S")
  filename = "Collection_at_" + time + ".csv"
  respond_to do |format|
    format.html
    format.csv { send_data @problems.to_csv, filename: filename }
  end
end

problem/index.html.erb

<span class="button">
  <p>
    <%= link_to "Download", problems_path(format: "csv"),class: "btn btn-success"  %>
  </p>
</span>

schema.rb

create_table "problems", force: :cascade do |t|
  t.datetime "detected_at"
  t.text "description"
  t.string "lob"
  t.string "status"
  t.string "productid"
  t.string "productname"
  t.string "crno"
  t.string "link"
  t.string "supplier"
  t.integer "user_id"
  t.datetime "created_at", null: false
  t.datetime "updated_at", null: false
  t.index ["user_id"], name: "index_problems_on_user_id"
end

自己学习一下 CSV 的格式,然后手拼 CSV

写个 self. to_csv 方法 想往里写什么就写什么

3 Floor has deleted
Reply to yfscret

嗯嗯,写出来了!

You need to Sign in before reply, if you don't have an account, please Sign up first.