[英]Using form to update has_many through join table
我缺乏 Rails 項目的實現想法。 在這一點上似乎不可能在 rails 中實現。
我正在使用 Rails 框架將一種會計軟件克隆到 Web 應用程序中,以供小型制造公司跟蹤其不同分銷分支中的產品庫存。
我有 3 種不同的模型:“產品”、“分支”和“累加器”
class Branch < ActiveRecord::Base
has_many :accumulators
has_many :products, :through => :accumulators
end
class Product < ActiveRecord::Base
has_many :accumulators
has_many :branches, :through => :accumulators
def self.search(search)
if search
where('name LIKE ?', "%#{search}%")
end
end
class Accumulator < ActiveRecord::Base
belongs_to :product
belongs_to :branch
end
我是 Rails 的新手,在閱讀了許多關聯之后,我發現使用集合將產品添加到分支“@branch.products << Product.all”
是否有可能在分支顯示視圖中使用表單“number_field_tag”將多個特定產品添加到連接表中?
例如,我想使用分支顯示視圖中的表單將 10 個稱為“花園雞蛋”的(產品)添加到名為“拉各斯分支”的(分支)到(累加器)連接表中?
恭喜您選擇:has_many, through:
您不會后悔。
product
和branch
之間的關系是靜態的嗎? 還是變化很大?
在您的Accumulator
模型中,添加一個名為amount
的integer
字段(計數可能存在沖突)。 然后你要么為你的Accumulators
創建一個表單,要么添加一個嵌套的表單,例如Cocoon 。
通過這種方式,您可以使用特定Product
和特定amount
將Accumulators
添加到您的Branch
。
題外話:
這是一篇關於為什么has_many through
有一些優勢的文章: http : //blog.flatironschool.com/why-you-dont-need-has-and-belongs-to-many/
如果您對表單有疑問,我真的可以推薦SimpleForm ,對於漂亮的 Javascript 輔助字段,我推薦Select2 。
如果表accumulators
只需要保存兩件事: product_id
和branch_id
,您可以輕松使用has_and_belongs_to_many
關聯。
class Branch < ActiveRecord::Base
has_and_belongs_to_many :products, join_table: 'accumulators'
end
class Product < ActiveRecord::Base
has_and_belongs_to_many :branches, join_table: 'accumulators'
end
現在,不需要第三個模型了。
至於如何添加關系,在這種情況下很容易:
branch = Branch.last
branch.products << Product.create # you don't need to touch the middle table.
您可以使用像jQuery Chosen Plugin這樣的奇特的東西,而不是使用number_field_tag
來請求普通的 id。 該插件將允許您使用標簽之類的輸入,並將 ID 發送到服務器,以,
分隔。
聲明:本站的技術帖子網頁,遵循CC BY-SA 4.0協議,如果您需要轉載,請注明本站網址或者原文地址。任何問題請咨詢:yoyou2525@163.com.