1

In my HTML, I am able to return an array from a select multiple box using

    <select multiple id="purchases" name="purchases[]">
    <option value="purchase1">Shoes</option>
    <option value="purchase2">Dress Shirts</option>
    </select>  

My goal is to create a new database record for each of the options selected (I'm using Ruby on Rails and MySQL.) However, my controller isn't saving each value in its own record:

Controller

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

Purchase Model

    class Purchase < ActiveRecord::Base
belongs_to :customer
    end

Customer Model

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

I know I should iterate through the controller, but I'm not sure how. Thanks in advance for your advice!

Edit 1

No matter what I do in the controller, the log tells me that the whole array, "purchases", is being sent, not the individual records. Here is the log and here is the current controller.

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#Create

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

2 回答 2

0

你可以试试这个:

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

在 Purchase.new() 你应该把你想要的所有其他属性

于 2013-08-16T00:38:56.487 回答
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 中,但那里的代码应该可以工作......我提供的代码是否有任何异常/错误?

于 2013-08-16T00:44:43.190 回答