Ruby on Rails,从另一个模型创建记录

我在rails上使用这个文件上传程序用于ruby。 我上传了一些带有数字的文件进行统计分析。 文件模型称为filedb.In filedb.rb打开文件并分析数字(一些相关内容等)。 之后我需要将结果保存到一个名为results的表中。

只需在filedb.rb中写一下就聪明了:

@cell=Results.new(:cell_name =>filenames, :icorrelation=>intensities) @cell.save 

或者最好使用results_controller在表中创建记录? 以及类似这样的事情:results_controller.rb:

  def create @result = Result.new(params[:result]) if @result.save lalala else render :new end end 

虽然我不知道如何传递参数:结果到控制器

提前致谢

编辑:

filedbs_controller.rb:

  def analyse (filedb.where(analyse:no)).perform_analysis respond_to do |format| format.html { redirect_to :back } end end 

filedb.rb

 def self.perform_analysis list=Analysis.do_number_analyse if list!=nil results(list) end end def self.results(list) do somthing with list cell=Results.new(:cell_name =>filenames, :icorrelation=>intensities) cell.save end 

Analysis.do_number_analyse – 是另一个模型中的方法,其中所有计算都已完成

您的第一种方法应该没问题,您可以从文件模型中保存结果。

你不需要使用实例变量@,因为它被认为是将变量发送到视图,我无法想象你为什么需要这样。

总结一下,在filedb.rb中:

 # here you calculations and then cell = Result.new(cell_name: filenames, icorrelation: intensities) cell.save! 

小心模型,应该是单数(结果,而不是结果)。 如果你使用保存! 方法,用“!” 保存新单元格时,您将看到控制器抛出的任何错误。

希望有所帮助

编辑KATJA编辑后

关于如何达到FieldsController中的分析操作,我有点迷茫,我想你是在成功上传文件后发送浏览器的。 假设您公开的代码应该正常工作。

然而,它确实看起来有点复杂,也许你可以用更简单的方式达到相同的结果。 因为我不知道你的整个代码或许我遗漏了一些东西,但我做的是摆脱分析动作并通过Filedb模型中的after_create回调处理单元格创建。

 class Filedb < ActiveRecord::Base # associations, validation and accessible stuff goes here, and then: after_create :perform_analysis protected def perform_analysis list = Analysis.do_number_analyse results(list) unless list.nil? end def results(list) # I assume that here you are using 'list' to get 'filenames' and 'intensities' values, and then: cell = Result.new(cell_name: filenames, icorrelation: intensities) cell.save! end end 

after_create回调仅在实例创建时触发,因此这里优于after_save。

这样,您不需要在控制器中执行任何“分析”操作,因为在每次创建文件后将自动调用“perform_analysis”方法; 您的代码在模型中紧密结合在一起,如果您需要返回并更改某些内容,您可以在将来轻松查看流程。

说得通?

@user存在吗? 如果没有定义@user 。 这会给你错误。