首页
学习
活动
专区
圈层
工具
发布
社区首页 >问答首页 >Rails 4库存应用程序:数据库设计和嵌套表单的使用

Rails 4库存应用程序:数据库设计和嵌套表单的使用
EN

Stack Overflow用户
提问于 2016-02-05 22:02:46
回答 1查看 336关注 0票数 1

我构建了这个应用程序,它工作得很好,而且非常简单:https://github.com/ornerymoose/DeviceCount。它允许您为设备创建一个新条目,您可以在其中指定设备的计数(即,库存数量)。

现在,尽管这种方法有效,但有人告诉我,它需要基于“每个位置”。也就是说,您创建了一个条目,您将拥有10个文本字段(如果确实有10个设备。此数量永远不会更改,设备也不会更改),并且对于每个设备文本字段,您将输入该设备的计数。您将为下拉菜单选择位置。创建该条目后,您将拥有:

-1位置

-列出10个设备,所有设备都有自己的计数。

我正在苦苦思索如何设计这些模型。我应该有一个EntryDevice模型吗?单独的Count模型?

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

任何和所有的意见都是值得感谢的。

EN

回答 1

Stack Overflow用户

发布于 2016-02-05 22:58:10

听起来您最好使用Inventory连接模型(使用has_many :through):

代码语言:javascript
复制
#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):

代码语言:javascript
复制
#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

票数 1
EN
页面原文内容由Stack Overflow提供。腾讯云小微IT领域专用引擎提供翻译支持
原文链接:

https://stackoverflow.com/questions/35226094

复制
相关文章

相似问题

领券
问题归档专栏文章快讯文章归档关键词归档开发者手册归档开发者手册 Section 归档