1

有谁知道是否有一个简单的解决方案可以在 Rails 的表单中动态添加新选项到选择菜单?

动态表单 railscast ( http://railscasts.com/episodes/403-dynamic-forms ) 专注于根据在另一个选择菜单中所做的选择动态过滤第二个选择菜单,这不是我想要的。我正在寻找一种解决方案,其中表单仅包含一个选择菜单,并且可以在表单上添加新选项。

我觉得解决方案可能类似于嵌套模型表单 railscast ( http://railscasts.com/episodes/196-nested-model-form-revised ) 中提到的解决方案,但在该示例中,表单必须在值之前提交在数据库中更新。我希望用户能够添加一个新的选择菜单选项,然后在提交之前继续表单的其余部分。

在这个阶段,我还想避免使用 railscast jquery 自动完成解决方案,因为它使用文本字段而不是选择菜单。

目前,我认为解决方案在选择菜单旁边有一个“添加新”按钮。当单击按钮时,会打开一个模式,允许用户输入新的选择菜单选项然后保存(更新数据库),模式关闭并更新表单。我只是想知道现有的优雅解决方案是否已经存在。

任何帮助将不胜感激。

谢谢。

更新:

我还没有创建任何代码来实现它,但这是我的表单:

<%= simple_form_for @other, :html => { :class => 'form-horizontal' } do |f| %>  
<fieldset>
  <%= f.error_notification %>           
  <%= f.association :other_type, :include_blank => false %>      
  <%= f.input :cost%>
  <%= f.input :invoice %>             
  <%= f.input :notes, :input_html => {:class => "row-fluid"} %>
<%= f.error :base %>
<div id="eze_form_actions" class="form-actions">
  <%= f.submit nil, :class => 'btn btn-primary' %>
  <%= link_to 'Cancel', others_path, :class => 'btn' %>
</div>
</fieldset>    
<% end %>
4

1 回答 1

1

我在我们的 CMS 中为类别做了类似的事情,用户可以轻松地添加一个新类别,然后我们 POST 到服务器,它以 HTML 响应(通过部分呈现),然后我们将其注入到我们的复选框中。您可以轻松地复制它以用于您的目的:

要让它工作,你需要一个表单、一个端点和一些 javascript:

形式

不确定您的表单将包含哪些内容,但请使用常规表单助手并确保表单设置为remote: true.

终点

您的端点应该呈现一个部分,它应该只包含 .. 的 html,我们将呈现为一个字符串并传递回要添加的前端。

def endpoint
  # create your new model with the params
  @model = Model.create(some: attribute)
  if @model.errors.empty and @model.save
    render json: { html: render_to_string(partial: "path/to/partial", locals: { model: @model })
  end
end

** JavaScript **

$(form)
  .bind('ajax:success', function(data, status) {
    $(select).append(status.html)
  })

status.html 应该是这样的<option>...</option>,所以我们只是附加到我们的选择中。

让我知道这是否没有意义。我希望它有所帮助。

于 2013-03-25T16:37:44.630 回答