我已经在我的rails应用程序中为Deal模型实现了excel导入(使用电子表格和roo gems)。
交易模型属于用户和期刊。 我需要将current_user.id和@ journal.id归因于每个导入的交易。
这就是我现在所拥有的:
deals_controller.rb
def import
@user = current_user
Deal.import(params[:file])
redirect_to journals_path, notice: "Deals imported."
end
deal.rb
def self.import(file)
spreadsheet = open_spreadsheet(file)
header = spreadsheet.row(1)
(2..spreadsheet.last_row).each do |i|
row = Hash[[header, spreadsheet.row(i)].transpose]
deal = find_by_id(row["id"]) || new
deal.attributes = row.to_hash.slice(*accessible_attributes)
deal.save!
end
end
def self.accessible_attributes
['user_id', 'journal_id', 'date_in', 'date_out', 'ticker', 'type', 'open_price', 'close_price', 'quantity', 'revenue',]
end
def self.open_spreadsheet(file)
case File.extname(file.original_filename)
when ".csv" then Roo::Csv.new(file.path, nil, :ignore)
when ".xls" then Roo::Excel.new(file.path, nil, :ignore)
when ".xlsx" then Roo::Excelx.new(file.path, options={})
else raise "Unknown file type: #{file.original_filename}"
end
end
但在这种情况下,用户可以通过在excel文件中输入他们的user_id和journal_id来访问其他用户的日记。
从excel文件导入交易时,自动为每笔交易分配user_id和journal_id的最佳方法是什么?
答案 0 :(得分:0)
只需指定要分配给模型的值:
def self.import(file, user_id, journal_id)
spreadsheet = open_spreadsheet(file)
header = spreadsheet.row(1)
(2..spreadsheet.last_row).each do |i|
row = Hash[[header, spreadsheet.row(i)].transpose]
deal = find_by_id(row["id"]) || new
deal.attributes = row.to_hash.slice(*accessible_attributes)
deal.user_id = user_id
deal.journal_id = journal_id
deal.save!
end
end
在你的控制器中,只需传递所需的参数:
def import
Deal.import(params[:file], current_user.id, @journal.id)
redirect_to journals_path, notice: "Deals imported."
end