2016-02-05 52 views
1

我构建这个应用程序,它很好地工作,很简单:https://github.com/ornerymoose/DeviceCount。它允许您为指定设备计数(即库存量)的设备创建新条目。Rails 4库存应用:数据库设计和嵌套表格的使用

现在即使这样做有效,但我被告知它需要在“每个位置”的基础上。也就是说,您创建了一个条目,并且您将为设备输入10个文本字段(如果确实有10个设备,这个数量永远不会改变,设备也不会改变),并且对于每个设备文本字段,您将输入该设备的计数。您将选择位置作为下拉菜单。在创建该条目,你将有:

-1位置列出

-10设备,都用自己的计数。

我很努力地围绕着如何设计这些模型。我应该有EntryDevice模型吗?一个单独的Count模型?

这里嵌套的表单是最好的方法吗?

任何和所有输入赞赏。

+0

我认为这个问题太广泛了,但是基本上你想要一个新的模型,它属于'位置'和'has_many''设备' –

+0

它是如何太广泛?我提供了我所拥有的和我需要的地方的示例应用程序。不过谢谢你,这应该有所帮助:)我意识到这并不是非常困难,但我很难看出结构的可视化。 – DnfD

回答

1

听起来像是你最好用Inventory加盟模式(与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 

这将允许您设置的device的“量”为每个位置(将不得不使用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 do |f| %> 
    <%= f.text_field :name %> 
    <%= f.fields_for :inventories, Location.all do |i| %> 
    <%= i.number_field :qty %> 
    <% end %> 
    <%= f.submit %> 
<% end %> 

这将允许您创建一个新的Device和有它通过其Inventoryqty可用。

+0

嗨Rich,谢谢你的详细解答。我看到你在加入模型时会得到什么(我认为它在OP中并不清楚),但它不会被创建设备,它将成为位置(也许更好的词是'Entry' )。每个条目将具有:位置/名称,10个设备,10个计数。然后,您可以查看索引页上的每个条目。 – DnfD