Note that there are some explanatory texts on larger screens.

plurals
  1. POaccepts_nested_attributes_for to link to existing record, not create a new one
    primarykey
    data
    text
    <p>I have the following models</p> <pre><code>class Order &lt; AR::Base has_many :products accepts_nested_attributes_for :products end class Product &lt; AR::Base belongs_to :order has_and_belongs_to_many :stores accepts_nested_attributes_for :stores end class Store &lt; AR::Base has_and_belongs_to_many :products end </code></pre> <p>Now I have a order view where I want to update the shops for the product. The thing is that I only want to connect the products to the existing shops in my db, not create new ones.</p> <p>My form in the order view looks like this (using Formtastic):</p> <pre><code>= semantic_form_for @order do |f| = f.inputs :for =&gt; :live_products do |live_products_form| = live_products_form.inputs :for =&gt; :stores do |stores_form| = stores_form.input :name, :as =&gt; :select, :collection =&gt; Store.all.map(&amp;:name) </code></pre> <p>Although its nested it works fine. The problem is that, when I select a store and try to update the order (and the products and stores with it), Rails tries to create a new store with that name. I want it to just use the existing store and connect the product to that.</p> <p>Any help appreciated!</p> <p>EDIT 1:</p> <p>In the end I solved this problem in a very crude way:</p> <pre><code># 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 </code></pre> <p>EDIT 2:</p> <p>Pablo's solution is much more elegant and should be preferred over mine.</p>
    singulars
    1. This table or related slice is empty.
    plurals
    1. This table or related slice is empty.
    1. This table or related slice is empty.
 

Querying!

 
Guidance

SQuiL has stopped working due to an internal error.

If you are curious you may find further information in the browser console, which is accessible through the devtools (F12).

Reload