在我的 HTML 中,我可以使用
从多选框中返回一个数组 <select multiple id="purchases" name="purchases[]">
<option value="purchase1">Shoes</option>
<option value="purchase2">Dress Shirts</option>
</select>
我的目标是为每个选择的选项创建一个新的数据库记录(我使用的是 Ruby on Rails 和 MySQL。)但是,我的 Controller 没有将每个值保存在它自己的记录中:
Controller
@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
我知道我应该遍历 Controller ,但我不确定如何做。预先感谢您的建议!
编辑 1
无论我在 Controller 中做什么,日志都会告诉我正在发送整个数组“购买”,而不是单个记录。这是日志,这是当前 Controller 。
日志
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
最佳答案
如果您使用的是 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 中,但上面的代码应该可以工作...我提供的代码是否有任何异常/错误?
关于mysql - 我如何使用 Ruby 遍历一个数组,以便它在 MySQL 中保存单个记录?,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/18138574/