【问题标题】:Want to be able to make multiple row inserts based off two different values希望能够根据两个不同的值进行多行插入
【发布时间】:2015-07-11 08:35:43
【问题描述】:

是否可以根据两个不同的列值为一条记录创建多行?

示例:在我的模型条目表中,我有一个名为 full_range 的列,这将在 leave_startleave_end 日期之间选择日期,例如,假设我选择 05/01/15 作为我的 @ 987654325@ 日期和05/05/15 作为我的leave_end 日期,这将给我05/01/15, 05/02/15, 05/03/15, 05/04/15, 05/05/15 我的full_range

那么对于我的另一个名为range_days 的列,值将是5,这是因为我在05/01/1505/05/15 之间有5 天。

我想做的是根据range_days 拆分我的full_range 值,我想从我的完整范围内为每个日期插入多行,我猜range_days 会发挥作用来创造价值要创建的行数。

现在我只得到这样的一排..

ID     Created_at Full_range_date   emp_id    range_days  leave_start leave_end   full_range     
10686   1-May-15    5/1/2015         TEST1        5        05/01/15   05/05/15     05/01/15 05/02/15 05/03/15 05/04/15 05/05/15     

所以理论上我希望在我的数据库中看到的是这个,所以它首先查看full_range 并获取第一个日期,将其填入full_range_date 然后查看下一个和下一个...基于range_days 它执行 5 天,即 5 行。

ID     Created_at Full_range_date   emp_id    range_days  leave_start leave_end   full_range     
10686   1-May-15    5/1/2015         TEST1        5        05/01/15   05/05/15     05/01/15 05/02/15 05/03/15 05/04/15 05/05/15     
10687   1-May-15    5/2/2015         TEST1        5        05/01/15   05/05/15     05/01/15 05/02/15 05/03/15 05/04/15 05/05/15     
10688   1-May-15    5/3/2015         TEST1        5        05/01/15   05/05/15     05/01/15 05/02/15 05/03/15 05/04/15 05/05/15     
10689   1-May-15    5/4/2015         TEST1        5        05/01/15   05/05/15     05/01/15 05/02/15 05/03/15 05/04/15 05/05/15     
10690   1-May-15    5/5/2015         TEST1        5        05/01/15   05/05/15     05/01/15 05/02/15 05/03/15 05/04/15 05/05/15     

我怎么能这样做任何帮助将不胜感激!!!

我正在使用 rails 4.1.8

这里还有我的入口控制器。

class EntryController < ApplicationController



  def new
    @entry = Entry.new

    respond_to do |format|

      format.html# new.html.haml
      format.xml { render :xml => @entry }
   end
 end


  def create
    params.permit!
    @entry = Entry.new(params[:entry])
    @entry.t_d
    @entry.day_hours
    @entry.current_user = current_user

    respond_to do |format|

      if @entry.save
        if current_user.email.nil?
          @entry.create_totals
          format.html { redirect_to(entry_path( @entry ), :notice => 'Entry successfully created, but you will not recieve any notifications, because you email is blank!') }
          format.xml { render :xml => @entry, :status => :created, :location => @entry }
        else    
          @entry.create_totals
          EntryMailer.submit_for_approval(@entry).deliver
          format.html { redirect_to(entry_path( @entry ), :notice => 'Entry successfully created.') }
          format.xml { render :xml => @entry, :status => :created, :location => @entry }
        end 
      else
        format.html { render :action => "new" }
        format.xml  { render :xml => @entry.errors, :status => :unprocessable_entity }
      end
    end
  end

和我的入门模型

class Entry < ActiveRecord::Base

  self.primary_key = 'id' 
end 

根据给出的答案,我尝试了这个,但它仍然只创建了一行想要它做的是从 full_range 为每个日期创建一个新行

 def create
   params.permit!
   @entry = Entry.new(params[:entry])
   @entry.t_d
   @entry.day_hours
   @entry.current_user = current_user

   # send my email
   respond_to do |format|

     begin
       Entry.transaction do
         @entry.full_range.split(' ').each do |date|
           entry = Entry.new( @entry.attributes.to_options )
           entry.full_range = date
           entry.save!
         end
       end

       if current_user.email.nil?
         @entry.create_totals
         format.html { redirect_to(entry_path( @entry ), :notice => 'Entry successfully created, but you will not recieve any notifications, because you email is blank!') }
         format.xml { render :xml => @entry, :status => :created, :location => @entry }
       else
         @entry.create_totals
         EntryMailer.submit_for_approval(@entry).deliver
         format.html { redirect_to(entry_path( @entry ), :notice => 'Entry successfully created.') }
         format.xml { render :xml => @entry, :status => :created, :location => @entry }
       end

     rescue
       format.html { render :action => "new" }
       format.xml  { render :xml => @entry.errors, :status => :unprocessable_entity }
     end
   end
 end

只是为了咯咯笑,我试着像在我的入门模型中那样做一个原始的 sql 语句

这样插入了正确数量的行,但所有数据都完全匹配,没有任何变化。

  def trying_it_all
    @id = self.id
    @leave_end = self.leave_end.to_date
    @leave_start = self.leave_start.to_date
    @range_vals = self.range_days
    if !(self.range_days == 0)  
       range_days.times do 
      sql = "insert into entry values('#{@id}', '#{@c_d}', '#{@c_u}', '#{@emp_id}', '#{@range_vals}', 'N')"
      Entry.connection.execute(sql)
    end
  end

【问题讨论】:

    标签: ruby-on-rails ruby ruby-on-rails-4 rails-activerecord


    【解决方案1】:

    这是绝对可能的,并且在您的实施中需要考虑很多事情。首当其冲的将是您的#create 操作。您已经掌握了所需的所有信息,因此我个人将采用以下方法。

    首先,一次创建多条记录时,always use a transaction。如果您不熟悉,这个想法是只有在每条记录都成功保存时才会对数据库进行更改(因此,如果其中一条记录失败,它将回滚所有其他记录,从而防止您的数据变得不一致)。实现可能如下所示:

      def create
        params.permit!
        @entry = Entry.new(params[:entry])
        @entry.t_d
        @entry.day_hours
        @entry.current_user = current_user
    
        respond_to do |format|
    
          if # Condition here
    
            ActiveRecord::Base.transaction do
              # Create your records here
            end
    
          else
            # Indicate failure
          end
    
        end
      end
    

    现在,您可能会发现 if 语句没有列出任何条件。这是因为对于多个事务,我们需要一种更好的方法来响应它们是否成功,而不仅仅是@entry.save 的结果。最简单的方法是with a Begin/Rescue block(您可能会从更主流的语言中识别为 Try/Catch)。它看起来像这样:

    respond_to do |format|
    
      begin       
        ActiveRecord::Base.transaction do
          # Create your records here
        end
      rescue
        # Indicate failure
      end
    
    end
    

    它的工作方式是执行 Begin 块,然后开始交易。在事务内部,如果发生故障,我们将引发错误。整个事务会回滚,错误会让我们跳出 Begin 块,转而进入 Rescue 块。

    现在,在事务中,我们需要创建多条记录。这部分应该相当简单。我们需要使用循环来根据 range_days 创建许多记录。在事务中,我们想做这样的事情:

    (1..@entry.range_days).each do
      entry = Entry.new( @entry.attributes.to_options )
      entry.full_range_date = # Calculation to determine the date of this entry
      entry.save!
    end
    

    这将为each day in range_days 创建一个条目。循环中的第一行创建了一个与@entry 具有相同值的非实例变量。第二行是您将更改 full_range_date 值的位置。第三行使用 .save!函数,which has an important difference compared to the .save function;如果失败,它将引发错误。如果出现任何严重错误,这是一个触发器,可让您逃离 Begin 块并跳转到 Rescue 块。

    关于设置新 full_range_date 的计算,这将涉及日期函数或字符串操作(取决于您处理日期的方式)。 请参阅答案底部的我的 REVISION 以了解如何完成此操作。因此,基本上,您的 create 函数可能看起来很像这样:

    def create
        params.permit!
        @entry = Entry.new(params[:entry])
        @entry.t_d
        @entry.day_hours
        @entry.current_user = current_user
    
        respond_to do |format|
    
          begin       
            ActiveRecord::Base.transaction do
              (1..@entry.range_days).each do
                entry = Entry.new( @entry.attributes.to_options )
                entry.full_range_date = # Calculation to determine the date of this entry
                entry.save!
              end
            end
    
            if current_user.email.nil?
              @entry.create_totals
              format.html { redirect_to(entry_path( @entry ), :notice => 'Entry successfully created, but you will not recieve any notifications, because you email is blank!') }
              format.xml { render :xml => @entry, :status => :created, :location => @entry }
            else    
              @entry.create_totals
              EntryMailer.submit_for_approval(@entry).deliver
              format.html { redirect_to(entry_path( @entry ), :notice => 'Entry successfully created.') }
              format.xml { render :xml => @entry, :status => :created, :location => @entry }
            end 
    
          rescue
            format.html { render :action => "new" }
            format.xml  { render :xml => @entry.errors, :status => :unprocessable_entity }
          end
    
        end
    end
    

    结束评论

    params.permit!是一种非常诱人的使用方法,因为它使您不必担心强参数,或者当您的模型更改时需要更新控制器......但它非常危险。用户不仅可以将您不期望的字段传递给您(从而迫使您处理您没有准备好的大量数据),它还允许精明的用户定义隐藏字段。例如,如果我向您的条目发送了一个 POST 请求,我可以指定 { :Created_At => 1-Jan-2015 },使它看起来像是我在四个月前创建了这条记录,并完全贬低了该列。在这种情况下,这并不重要,但假设您有一个带有 :is_administrator 字段的 User 模型。然后任何人都可以创建具有管理权限的用户。 This may be worth reading,如果你有兴趣。

    修订

    快速补充!如果你的 full_range 变量中已经有 Full_range_date 值,你可以用这个替换原来的循环:

    @entry.full_range.split(' ').each do |date|
      entry = Entry.new( @entry.attributes.to_options )
      entry.full_range_date = date
      entry.save!
    end
    

    这会将 full_range 值转换为数组,遍历每个元素,并为您设置 full_range_date 的值,无需进一步计算。

    【讨论】:

    • 我试过了,但它仍然只排一行。谢谢你提供的所有有用的东西! @ConnorCMcKee
    • 您能否为您的问题添加一个修订版,其中包含您的创建操作现在的样子?如果您可以准确显示您传递给它的参数以及创建了哪些记录,这也可能会有所帮助。谢谢!
    • 谢谢!我没有看到的唯一部分是您传递给它的确切值以及创建的内容。这会很有帮助,因为这样我们就可以确切地看到正在发生的事情。或者,您可以尝试使用debug 命令来查看循环中正在处理的值。 ID 没有作为参数传递,是吗?如果是这样,那么我们只需更新相同的记录,而不是创建新记录。
    猜你喜欢
    • 2020-02-06
    • 2022-11-19
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 2023-03-11
    • 2012-12-21
    相关资源
    最近更新 更多