我的 Rails 应用程序中的当前模型代码使用“文本”作为键,然后根据天气更新或创建新行,它是否重复。我正在寻找应将所有行导入数据库的替换代码(因此无需使用文本作为键,可以接受重复的内容)。有谁知道如何做到这一点?
路线.rb
MyApp::Application.routes.draw do
resources :users do
member do
get :following, :followers
end
end
resources :sessions, only: [:new, :create, :destroy]
resources :microposts, only: [:create, :destroy]
resources :relationships, only: [:create, :destroy]
resources :password_resets
resources :banklines, only: [:create, :destroy]
resources :booklines, only: [:create, :destroy]
root to: 'static_pages#app'
post '/upload_booklines', to: 'booklines#upload_booklines'
match '/board', to: 'static_pages#home'
match '/signup', to: 'users#new'
match '/signin', to: 'sessions#new'
match '/signout', to: 'sessions#destroy', via: :delete
match '/help', to: 'static_pages#help'
match '/about', to: 'static_pages#about'
match '/contact', to: 'static_pages#contact'
控制器/booklines_controller.rb
class BooklinesController < ApplicationController
require 'csv'
def upload_booklines
if request.post? && params[:file].present?
infile = params[:file].read
n, errs = 0, []
CSV.parse(infile) do |row|
n += 1
next if n == 1 or row.join.blank?
@bookline = current_user.booklines.build_from_csv(row)
if @bookline.valid?
@bookline.save
else
errs << row
end
end
redirect_to root_path
end
end
模型/bookline.rb
class Bookline < ActiveRecord::Base
attr_accessible :amount, :appendix_number, :date, :text
belongs_to :user, dependent: :destroy
scope :active, where(:active => true)
scope :latest, order('created_at desc')
def self.build_from_csv(row)
bookline = find_or_initialize_by_text(row[1])
bookline.attributes ={:date => row[0], :amount => row[2], :appendix_number => row[3]}
return bookline
end
end
视图/static_pages/app.html.erb
<%= form_tag('upload_booklines', :multipart => true) do %>
<p>
File:<br />
<%= file_field_tag 'file' %><br />
</p>
<p>
<%= submit_tag "Upload" %>
</p>
<% end %>