You need to enable JavaScript to run this app.
优惠活动
大模型
产品
解决方案
定价
更多

如何在Ruby视图中设置只读属性?使用:readonly=>true未生效求助

解决Ruby视图中calendar_date_select_tag只读属性不生效的问题

calendar_date_select_tag 这类日期选择器助手通常不会直接识别顶层的 :readonly 参数,你需要把HTML属性(比如readonly)放到专门的:html选项哈希里,试试修改代码如下:

<div class="row form-group">
  <div class="col-md-2">
    <%='start_date'%><span class="necessary-field">  *</span>:
  </div>
  <div class="col-md-6 select">
     <%= calendar_date_select_tag 'start_date', @employee.job.start_date, 
         :format => :default, :popup => "force", :class => "form-control",
         :html => {:readonly => true} %>
  </div>
</div>

如果还是不生效,可检查页面是否有JavaScript代码动态移除了readonly属性——部分日期选择器插件会自动覆盖这类属性,这种情况可以通过自定义CSS或JS强制锁定输入;另外如果不需要提交该字段值,也可以尝试用:disabled => true(注意disabled会让表单不提交该字段的值,需根据需求选择)。


以input标签为例实现只读效果

分两种场景实现:

1. 纯HTML的input标签

直接在标签内添加readonly属性(HTML5中可仅写readonly,无需赋值):

<!-- 普通文本输入框只读 -->
<input type="text" name="username" value="test_user" readonly>

<!-- 日期输入框只读 -->
<input type="date" name="start_date" value="2024-01-01" readonly>

2. Rails表单助手写法

  • 使用text_field_tag时,直接在参数末尾添加:readonly => true:
    <%= text_field_tag 'username', 'test_user', :readonly => true, class: 'form-control' %>
    
  • 使用form builder(如f.text_field)时的写法:
    <%= form_for @user do |f| %>
      <%= f.text_field :username, readonly: true, class: 'form-control' %>
    <% end %>
    

注意:readonly属性仅限制用户编辑,表单提交时会携带该字段的值;若使用disabled属性,用户同样无法编辑,但表单不会提交该字段的值,需根据业务需求选择。

内容的提问来源于stack exchange,提问作者amine bougrine

相关产品推荐
方舟 Agent Plan

超全模态模型 × Harness 升级,最新支持 Deepseek-V4.1-Flash、GLM-5.3 系列、Doubao-Seedream-5.0-pro、Kimi-K3 (部分), 限时 9.9 元起

最近更新时间:2026.08.18 04:50:11