Rails将数组保存到数据库

时间:2016-11-17 13:29:16

标签: ruby-on-rails arrays

有人可以查看我的代码,让我知道是否有更好的方法可以做到这一点,或者甚至纠正我出错的地方吗?我正在尝试为每个场地和变体创建一个新行。

示例:

venue_ids => ["1","2"], variant_ids=>["10"]

所以,我想添加一个venue_id of 1variant_id of 10的行。还有一个venue_id of 2variant_id of 10

我得到了这个工作,它现在正在我的两个阵列中传递。我想我几乎就在那里我不确定.each是否是正确的做法,但我认为我走在了正确的轨道上哈哈。我提交了,但是,我会把@back_bar.save放在哪里?因为这可能会导致问题,因为它不会重定向

提前致谢。

def create
  @back_bar = BackBar.new
  @venues = params[:venue_ids]
  @productid = params[:product_id]
  @variants = params[:variant_ids]

  # For each venue we have in the array, grab the ID.
  @venues.each do |v|
    @back_bar.venue_id = v
    # Then for each variant we associate the variant ID with that venue.
    @variants.each do |pv|
      @back_bar.product_variant_id = pv

      # Add in our product_id
      @back_bar.product_id = @productid
      # Save the venue and variant to the DB.

      if @back_bar.save
        flash[:success] = "#{@back_bar.product.name} has been added to #{@back_bar.venue.name}'s back bar."
        # Redirect to the back bar page
        redirect_to back_bars_path
      else
        flash[:alert] = "A selected variant for #{@back_bar.product.name} is already in #{@back_bar.venue.name}'s back bar."
         # Redirect to the product page
        redirect_to discoveries_product_path(@back_bar.product_id)
      end
    end # Variants end
  end # Venues end
end

private

  def back_bar_params
    params.require(:back_bar).permit(:venue_id,
                                     :product_id,
                                     :product_variant_id)
  end

1 个答案:

答案 0 :(得分:2)

正如我在评论中所说的

这是未经测试的代码,只是向您展示如何轻松完成。

class BackBar

  def self.add_set(vanue_ids, variant_ids)
    values = vanue_ids.map{|ven|
      variant_ids.map{|var|
        "(#{ven},#{var})"
      }
    }.flatten.join(",")

    ActiveRecord::Base.connection.execute("INSERT INTO back_bars VALUES #{values}")
  end
end

def create
  # use in controller
  BackBar.add_set(params[:venue_ids], params[:variant_ids])

  # ...
end