I have two models, Item and Bid
class Item
include Mongoid::Document
field :name, type: String
has_many :bids
end
class Bid
include Mongoid::Document
include Mongoid::Timestamps::Created
field :bid, type: Float
field :bidder, type: String
belongs_to :item
end
In views/prices/index I would like to list all items in a table and for each item put a field next it in which people can enter a number. At the bottom of the form should be a submit button for all records.
How is this best achieved?
There’s plenty of code out there explaining how to add, for instance, several questions to one survey (http://railscasts.com/episodes/196-nested-model-form-part-1) but I couldn’t find an example that shows how to add one new record for each of an existing element of a collection.
I don’t think you need to dynamically add a form for each item if you know you are going to use all of the items there to begin with.
Quick and Dirty:
I haven’t tried this and that code isn’t tested, but I would assume if you do some work in the controller to build each bid it should be fine. Also amount would be a better variable name for the bid class than using Bid.bid.
The proper way to do this (which would also allow updates) would be to make a nested form and then use
fields_formethod to actually look at a live bid object: http://archives.ryandaigle.com/articles/2009/2/1/what-s-new-in-edge-rails-nested-attributes