首页 > 解决方案 > 当视图中存在 f.association 时,simple_form 中的选定下拉菜单

问题描述

您能否告诉我是否有一种方法可以在 Rails 中使用 simple_form,当视图中存在“f.associations”时,禁用表单中选定的下拉菜单但仍使用该字段的预填充值?

我尝试使用选项“:disabled => true”,但它禁用了整个文本字段,并且我需要一个值出现在这里。当我提交表单时,我收到一个应该存在值的错误。

我尝试使用选项“:as => :hidden”,输入值没有出现,但是当我提交表单时,我收到一个应该存在值的错误。

我试过选项“:readonly => true”,但下拉菜单仍然出现。它显示为灰色,但仍然可以选择。

谢谢你,西尔维

标签: ruby-on-railsdrop-down-menusimple-form

解决方案


使用隐藏的具有相同变量和值的输入 f.association 禁用,提交表单时,将立即发送需要的值。

示例代码说明了这种情况,注意行f.association :company获取值company_id但不发送,因此f.input :company_id将替换,并且有效!

Welcome to project railstrace !
<p>Simple Form content: </p>
<%= simple_form_for @user, url: save_path, :method => :post do |f| %>
  <%= f.input :email %>
  <%= f.association :company, disabled: true %>
  <%= f.input :company_id, :as => :hidden, :input_html => {:value => @user.company_id} %>
  <%= f.association :roles %>
  <%= f.button :submit %>
<% end %>

推荐阅读