如何使用Ruby迭代数组,以便在MySQL中保存单个记录?

时间:2013-08-09 00:50:39

标签: mysql ruby-on-rails ruby

在我的HTML中,我可以使用

从选择的多个框中返回一个数组
    <select multiple id="purchases" name="purchases[]">
    <option value="purchase1">Shoes</option>
    <option value="purchase2">Dress Shirts</option>
    </select>  

我的目标是为所选的每个选项创建一个新的数据库记录(我正在使用Ruby on Rails和MySQL。)但是,我的控制器没有将每个值保存在自己的记录中:

控制器

    @purchase = Purchase.new(params[:purchases])
    @purchase.purchaseinfo = params[:purchases]

购买模式

    class Purchase < ActiveRecord::Base
belongs_to :customer
    end

客户模式

    class Customer < ActiveRecord::Base
belongs_to :account
    has_many :purchases
    end

我知道我应该遍历控制器,但我不确定如何。提前感谢您的建议!

修改1

无论我在控制器中做什么,日志都会告诉我整个阵列“购买”正在发送,而不是单个记录。这是日志,这是当前的控制器。

LOG

    Processing SavedcustomerController#create (for IP at DATE TIME) [POST]
    Parameters: {"purchases"=>["Item1", "Item2", "Item3"]}
    Redirected to http://example.com/maptry
    Completed in 21ms (DB: 2) | 302 Found [http://example.com/]

SavedcustomerController#创建

items_array = params[:purchases].split('"\"\"",')
items_array.each do |arrayitem| 
  @purchase = Purchase.new(params[:purchases])
      @purchase.purchaseinfo = arrayitem
  end

2 个答案:

答案 0 :(得分:0)

你可以试试这个:

items_array = params[:purchases]
items_array.each do |arrayitem| 
  @purchase = Purchase.new()
  @purchase.purchaseinfo = arrayitem
end

在Purchase.new()中,您应该放置所需的所有其他属性

答案 1 :(得分:0)

如果您使用的是Rails 3,并且将attr_accessible :purchase_info添加到Purchase型号,则可以执行此操作。

purchases = params[:purchases]
@purchases = purchases.map { |purchase| Purchase.create(purchase_info: purchase) }

<强>更新 以最简单的方式,你应该能够做到

purchases = params[:purchases]
purchases.each do |purchase_info|
  purchase = Purchase.new
  purchase.purchase_info = purchase_info
  purchase.save
end

我不确定attr_accessible是否在Rails 2中,但那里的代码应该有用......你在我提供的代码中是否有任何异常/错误?