oluşturmaz, mevcut kayda bağlamak Ben Şimdi bir düzen görünüme sahipaccepts_nested_attributes_for yenisi
class Order < AR::Base
has_many :products
accepts_nested_attributes_for :products
end
class Product < AR::Base
belongs_to :order
has_and_belongs_to_many :stores
accepts_nested_attributes_for :stores
end
class Store < AR::Base
has_and_belongs_to_many :products
end
aşağıdaki modeller nerede ürün için dükkan güncellemek istiyorum var. İşin aslı, ürünlerimi sadece mevcut olan mağazalara bağlamak istiyorum. Sipariş görünümünde
Benim formu (formtastic kullanarak) aşağıdaki gibidir:
= semantic_form_for @order do |f|
= f.inputs :for => :live_products do |live_products_form|
= live_products_form.inputs :for => :stores do |stores_form|
= stores_form.input :name, :as => :select, :collection => Store.all.map(&:name)
onun iyi çalışıyor iç içe rağmen. Sorun şu ki, bir mağaza seçtiğimde ve siparişi güncellemeyi denediğimde (ve onunla ürünler ve mağazalar), Rails bu isimle yeni bir mağaza oluşturmaya çalışır. Sadece mevcut mağazayı kullanıp ürünü ona bağlamak istiyorum.
Herhangi bir yardım için teşekkür ederiz!
DÜZENLEME 1:
# ProductsController
def update
[...]
# Filter out stores
stores_attributes = params[:product].delete(:stores_attributes)
@product.attributes = params[:product]
if stores_attributes.present?
# Set stores
@product.stores = stores_attributes.map do |store_attributes|
# This will raise RecordNotFound exception if a store with that name doesn't exist
Store.find_by_name!(store_attributes[:name])
end
end
@order.save
[...]
end
DÜZENLEME 2: Bir çok kaba bir şekilde bu sorun çözülür Sonunda
Pablo'nun çözeltisi daha zarif ve maden tercih edilmelidir .
a_n_a_f (http://api.rubyonrails.org/classes/ActiveRecord/NestedAttributes/ClassMethods.html) Ben update_only seçeneği görünce ilk heyecan var ama çabuk fark Dokümanları inceledikten sonra hiçbir yolu yoktur Ne yapmak istediğimi yapmak için (yenilerini oluşturmadan önce update_only mevcut nesneleri günceller). –