开发者

Creating items in groups in Rails

My product table is

id        type         price      location
1         chips         $3         开发者_高级运维 aisle3

I have a question with adding the products in groups. There is a quantity field(nonmodel) where the user can enter the quantity While adding a new product if the user enters:

type: soda
quantity: 3

Then there 3 records should be created in product model with type= soda like the following.

id   type   
2    soda  
3    soda   
4    soda   

If user enters

location: aisle4
quantity: 2

Then

id   location  
5    ailse4
6    ailse4

Can you tell me how to pass the nonmodel field 'quantity' to the rails(model or controller) and how use it to add the products in groups as mentioned above? or should I create a column called quantity in my product table? Will the history be updated too for all these new records with after_create filter which I already have ? Is there any good tutorial or book which shows how to pass such nonmodel html/javascript fields from view to rails and then back to the view? Any help will be greatly appreciated. Thanks


Try this:

class Product < ActiveRecord:Base

  attr_accessor :quantity


  def self.create_in_group(params)
    size, i = params["quantity"].to_i, 0
    size.times { Product.create(params);i+=1 }  
    i == size
  end

end

class ProductsController < ApplicationController

  def create
    if Product.create_in_group(params[:product])
      # success
    else
      # error
    end
  end

end

PS: In your view you can access the quantity field as though it is a product model field.

0

上一篇:

下一篇:

精彩评论

暂无评论...
验证码 换一张
取 消

最新问答

问答排行榜