开发者

Ruby on Rails: How to add a form text field if the corresponding filed in the model doesn't exist?

开发者 https://www.devze.com 2023-01-30 15:45 出处:网络
I have the following models: Product: name, shop_id (foreign key) Shop:name The associations are: Product: belongs_to :shop

I have the following models:

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

The associations are:

Product: belongs_to :shop
Shop:    has_many   :products

In the form that creates a new Product I have:

<%= f.label(:shop, "Shop:") %>
<%= f.sele开发者_开发技巧ct(...) %>

This is a select box with all existing shops. The last option in this select box is Create New Shop. When user clicks this option, Javascript shows an extra field:

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

(This div is hidden by default with display: none.)

How should I add this div in the Rails form creation ?

I tried:

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

but it doesn't work because new_shop is not Product's field.

I thought to use:

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

but I don't know what to use.

Please advise.


Try

<%= text_field_tag("new_shop") %>  


In fact, you could add your method in the model:

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

精彩评论

暂无评论...
验证码 换一张
取 消

关注公众号