Rails 4 Inventory Application: database design and use of nested forms -
i built application , works nicely , quite simple: https://github.com/ornerymoose/devicecount . allows create new entry device specify count (ie, inventory amount) of device.
now though works, i've been told needs on 'per location' basis. ie, create entry , have 10 textfields (if there indeed 10 devices. amount never change nor devices change) devices, , each device text field, enter count device. choose location dropdown menu. when entry created, have:
-1 location
-10 devices listed, own count.
i'm struggling wrapping head around how design these models. should have entry
, device
model? separate count
model?
would nested form best approach here?
any , input appreciated.
sounds you'd best inventory
join model (with has_many :through
):
#app/models/inventory.rb class inventory < activerecord::base # id | device_id | location_id | qty | created_at | updated_at belongs_to :device belongs_to :location end #app/models/device.rb class device < activerecord::base has_many :inventories has_many :locations, through: :inventories accepts_nested_attributes_for :inventories end #app/models/location.rb class location < activerecord::base has_many :inventories has_many :devices, through: :inventories end
this allow set "quantity" of device
each location (will have use accepts_nested_attributes_for
):
#app/controllers/devices_controller.rb class devicescontroller < applicationcontroller def new @device = device.new @locations = location.all end def create @device = device.new device_params @device.save end private def device_params params.require(:device).permit(inventories_attributes: [:qty]) end end #app/views/devices/new.html.erb <%= form_for @device |f| %> <%= f.text_field :name %> <%= f.fields_for :inventories, location.all |i| %> <%= i.number_field :qty %> <% end %> <%= f.submit %> <% end %>
this allow create new device
, have it's qty
available through inventory
.
Comments
Post a Comment