将上传的CSV文件中的行与rails中的用户相关联

我正在关注http://railscasts.com/episodes/396-importing-csv-and-excel的上半部分来上传CSV文件并在我的rails应用程序中创建新的“示例”。

我正在尝试创建一个仅显示当前用户样本的mysamples页面。 到目前为止,如果我通过表单一次添加一个样本,它将显示在此页面上。

但是当我上传CSV时,新样本没有与用户关联。

有关最佳方法的建议吗?

谢谢你的帮助。

Sample_Controller.rb

class SamplesController  params[:page], :per_page => 10 ) respond_with(@samples) authorize @samples end def mysample @samples = Sample.all authorize @samples end def import @samples = Sample.all if params[:file].present? Sample.import(params[:file], params[:user_id]) redirect_to root_url, notice: "Samples Imported" else redirect_to root_url, notice: "You need to choose a file first!" end authorize @samples end def show respond_with(@sample) end def new @sample = Sample.new respond_with(@sample) authorize @sample end def edit end def create params[:sample][:user_id] = current_user.id @sample = Sample.new(sample_params) authorize @sample if @sample.save redirect_to @sample, notice: 'Sample was successfully created.' else render action: 'new' end end def update if @sample.update(sample_params) redirect_to @sample, notice: 'Sample was successfully updated.' else render action: 'edit' end 

结束

 def destroy @sample.destroy authorize @sample respond_with(@sample) end private def set_sample @sample = Sample.find(params[:id]) authorize @sample end def sample_params params.require(:sample).permit(:line, :season, :style, :color, :date_out, :to_who, :date_in, :location,:user_id) end 

结束

Sample.rb模型

class Sample <ActiveRecord :: Base belongs_to:user

 def self.import(file, user_id) CSV.foreach(file.path, headers: true) do |row| Sample.create! row.to_hash end end end 

mysample.html.erb

 
Line
Season
Style
Color
Date Out
To Who
Date In
Location

编辑我使用byebug来逐步完成模型并且没有任何错误。 但是我最后一次这样做,我退出了byebug,关闭了服务器,重启了它并点击了这个url刷新http:// localhost:3000 / samples / import

这导致了一个我没见过的错误。 在此处输入图像描述

您没有传入用户ID,因此将user_id合并到您的哈希:

 def self.import(file, user_id) CSV.foreach(file.path, headers: true) do |row| Sample.import(params[:file], current_user.id) end end end 

您可以找到用户并通过关联来确保用户存在 – 您希望如何处理它不存在我留给您。 使用find_by所以它不会抛出活动记录未找到错误,如果你想要那么只需使用find。

 def self.import(file, user_id) user = User.find_by(id: user_id) if user CSV.foreach(file.path, headers: true) do |row| user.samples.create! row.to_hash end end end end