【问题标题】:Ruby on Rails: How to add a form text field if the corresponding filed in the model doesn't exist?Ruby on Rails:如果模型中的相应字段不存在,如何添加表单文本字段?
【发布时间】:2010-12-14 00:55:32
【问题描述】:

我有以下型号:

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

这些关联是:

Product: belongs_to :shop
Shop:    has_many   :products

在创建新Product的表单中我有:

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

这是一个包含所有现有商店的选择框。此选择框中的最后一个选项是Create New Shop。当用户点击此选项时,Javascript 会显示一个额外的字段:

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

(这个div默认隐藏在display: none中。)

我应该如何在 Rails 表单创建中添加这个 div

我试过了:

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

但它不起作用,因为new_shop 不是Product 的字段。

我想用:

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

但我不知道该用什么。

请指教。

【问题讨论】:

  • 如果你的问题的标题是一个问题,你可能会得到更多的关注:-)

标签: ruby-on-rails forms ruby-on-rails-3


【解决方案1】:

试试

<%= text_field_tag("new_shop") %>  

【讨论】:

    【解决方案2】:

    事实上,你可以在模型中添加你的方法:

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

    【讨论】:

      猜你喜欢
      • 1970-01-01
      • 2020-05-19
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      • 2011-05-18
      • 1970-01-01
      相关资源
      最近更新 更多