【发布时间】:2014-06-17 08:40:15
【问题描述】:
我有一个类似图书馆的预订系统。我想制作一个用于添加库存书籍的表单,允许用户选择一本书并选择一个图书馆(两者都是 collection_select)。 Book 通过 stock_items 表与 Library 具有多对多的关系。
我想不通的是如何引入数量,以便用户可以将同一本书的多个实例添加到所选大学。我应该如何实现这种数量类型的功能。它应该在连接表中创建选定数量的记录。
这是我的表单(目前一次只创建 1 个实例):
<%= form_for(@item) do |f| %>
<%= f.label :choose_book %>
<%= f.collection_select(:book_id, Book.all, :id, :name, prompt: true) %>
<%= f.label :choose_library %>
<%= f.collection_select(:library_id, Library.all, :id, :name, prompt: true) %>
<%= f.submit "Add item in stock", class: "btn btn-info" %>
<% end %>
StockItem 模型
class StockItem < ActiveRecord::Base
belongs_to :library
belongs_to :book
has_many :bookings, foreign_key: :stock_id, dependent: :destroy
validates :availability, presence: true
validates :library_id, presence: true
end
库模型
class Library < ActiveRecord::Base
has_many :stock_items
has_many :books, through: :stock_items
end
图书模型
class Book < ActiveRecord::Base
validates :year_of_publication, presence: true, length: { maximum: 4 }
validates :description, presence: true, length: { minimum: 10 }
validates :name, presence: true
has_many :stock_items, dependent: :destroy
has_many :libraries, through: :stock_items
has_many :contributions, dependent: :destroy
has_many :authors, through: :contributions
has_many :bookings, through: :stock_items
has_many :book_images, dependent: :destroy
accepts_nested_attributes_for :book_images
accepts_nested_attributes_for :authors
accepts_nested_attributes_for :libraries
accepts_nested_attributes_for :stock_items
accepts_nested_attributes_for :contributions
validates :name, presence: true
end
StockItemsController 的一点点
def create
@item = StockItem.new(item_params)
if @item.save
flash[:success] = "Item added to stock"
redirect_to stock_items_path
else
flash[:danger] = "Item has not been added to stock!"
render 'new'
end
end
def new
@item = StockItem.new
end
private
def item_params
params.require(:stock_item).permit(:library_id, :book_id, :availability)
end
【问题讨论】:
-
首先你必须在你的 stock_item 表中添加数量属性来存储数量..
-
@Gagan 这取决于 StockItem 是代表“图书馆中同一本书的集合”还是代表一本实体书。如果是后者,那么数量不起作用。我认为他需要扩展他的模式,以便为“图书馆中同一本书的集合”提供单独的模型,这会有数量,以及单独的库存项目的单独模型(即单独的书籍签出)。
-
@MaxWilliams : 感谢您的回复.. 我也可以学习这个东西,因为我是新蜜蜂..
标签: ruby-on-rails ruby-on-rails-4 form-for