我想让用户可以使用HTML输入来上传CSV文件,或者将列数据复制并粘贴到文本框中,然后创建一个CSV文件,以将其保存到模型中。
您知道任何好的库或实用方法如何解决此问题吗?
答案 0 :(得分:1)
使用ActiveStorage
假设您已经set up ActiveStorage
,
app / models / foo.rb
class Foo < ApplicationRecord
has_one_attached :csv
# sets `csv` attachment from a String input
# i.e. value = "Name,Age,\nBen,24,\nJenny,23,\nGeorge,21,\n"
def csv_string=(value)
tempfile = Tempfile.new
tempfile << value
tempfile.close
self.csv = ActionDispatch::Http::UploadedFile.new(
tempfile: tempfile,
type: 'text/csv',
filename: 'some_file_name.csv' # << change this filename accordingly
)
end
end
app / views / foos / _form.html.erb
<%= form_with(model: @foo, local: true) do |form| %>
<!-- ... -->
<%= form.file_field :csv %>
<%= form.text_area :csv_string %>
<!-- ... -->
<% end %>
app / controllers / foos_controller.rb
class FoosController < ApplicationController
def create
@foo = Foo.new(foo_params)
# ...
end
private
def foo_params
params.require(:foo).permit(:csv, :csv_string)
end
end
TODO
:csv_string
将覆盖csv
的值(如果用户输入了两者)