当视图中存在 f.association 时,simple_form 中的选定下拉菜单

问题描述

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

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

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

我已经尝试使用选项 ":readonly => true",但下拉菜单仍然出现。它显示为灰色,但仍然可以选择。

谢谢, 西尔维乌

解决方法

禁用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 %>