Ruby on Rails: how to add a form text field if the corresponding entry in the model does not exist?

I have the following models:

Product: name, shop_id (foreign key)
Shop:    name

Associations:

Product: belongs_to :shop
Shop:    has_many   :products

In the form that creates the new one Product, I:

<%= f.label(:shop, "Shop:") %>
<%= f.select(...) %>

This is a selection box with all existing stores. The last option in this selection field Create New Shop. When the user clicks this option, Javascript shows an additional field:

<div id="new_shop_wrapper">
    <label for="new_shop">New shop:</label>
    <input id="new_shop" name="new_shop" type="text" />
</div>

(This one divis hidden by default with display: none.)

How to add this divto Rails form creation?

I tried:

<%= f.label(:new_shop, "New Shop:") %>
<%= f.text_field(:new_shop) %>  

but it does not work because new_shopnot Product.

I thought to use:

<%= text_field(<object>, :new_shop) %>  

but I do not know what to use.

Please inform.

+3
2

Try

<%= text_field_tag("new_shop") %>  
+4

:

class Product < ActiveRecord::Base
  def new_show=(val)
    self.shop = Shop.new({:name => val})
  end
end
+2

Source: https://habr.com/ru/post/1780129/


All Articles