Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Form with dynamic number of items

Just thinking about the best way to build an Order form that would (from user-perspective):

  • Allow adding multiple items.
  • Each item has Name, Job Type drop-down and File upload.
  • User can add or remove items.
  • User must provide at least one item.
  • All the items should be validated (eg: Name, JobType and File are required).
  • When he hits the Submit, an Order should be created with all the items in it.

So the model looks like: User -1---*-Order-1---*- OrderItem-*--1-JobType. Additionally OrderItem includes number of attributes, let's say name, file.


Now I would like to have as skinny controller as possible. Better with the 'standard' code like:

class OrdersController < ApplicationController
  def create
    @order = Order.new(params[:order])
    if @order.save
      redirect_to account_url
    else
      flash.now[:error] = "Could not save Order"
      render :action => "new"
    end
  end
end

The most interesting thing is how a view should look like so that rails automatically binds all the values posted to the correct objects?

For now I don't worry about degradation from JavaScript, but rather the template for the items to be added and linking all that with the validation (probably as a partial).

I expect a template to look like the one below, but not sure.

<input type='text' name='order[order_items[name[]]][]' />
<select name='order[order_items[job_type[]]][]'>...</select>
<input type='file' name='order[order_items[file[]]][]' />

I have to clone this template in order to add item using JS.


So the answer should:

  • Include the view or part of it that demonstrates:
    • correct binding of the post values;
    • correct validation for all items;
  • Include related part of model.
  • Include changes to the controller IF and ONLY IF necessary.
  • (JavaScript is not required)

Ideally I would like to see a sample if somebody knows one (maybe somewhere on GitHub).

And the last note, please, check your solutions before posting.

Thanks,
Dmitriy.

like image 943
Dmytrii Nagirniak Avatar asked Jan 30 '26 17:01

Dmytrii Nagirniak


1 Answers

Not answering the question directly, but here are some sources to get you there:

  • Railscasts: Nested Model Form Part 1
  • Railscasts: Nested Model Form Part 2
  • Railscasts: Complex Forms Part 3

On a personal note. Your question comes across as asking for someone to do your work for you. I would gladly post an answer to cover all your needs if I was on the clock.

like image 54
Tony Fontenot Avatar answered Feb 01 '26 05:02

Tony Fontenot



Donate For Us

If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!