2016-02-05 26 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