聽起來像是你最好用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
和有它通過其Inventory
qty
可用。
我認爲這個問題太廣泛了,但是基本上你想要一個新的模型,它屬於'位置'和'has_many''設備' –
它是如何太廣泛?我提供了我所擁有的和我需要的地方的示例應用程序。不過謝謝你,這應該有所幫助:)我意識到這並不是非常困難,但我很難看出結構的可視化。 – DnfD