Ruby on Rails中Enum表单下拉映射及展示取值问题
解决方案
你遇到的两个问题都可以基于现有枚举定义直接解决,不需要硬编码:
1. 下拉选框简化+自动回填
你可以把枚举选项的映射逻辑抽到模型的类方法中,统一复用:
首先在Site模型中新增类方法:
def self.construction_type_options construction_types.map { |key, display_val| [display_val, key.to_s] } end
之后表单的下拉代码可以简化为:
<%= form.label(:construction_type, class: "form-label") %> <% options = options_for_select(Site.construction_type_options, form.object.construction_type) %> <%= form.select(:construction_type, options, include_blank: true) %>
新增、编辑页都可以复用同一个Site.construction_type_options,自动回填逻辑完全正常,不需要冗余映射,也不会有硬编码重复问题。
2. 详情页显示友好枚举值
直接调用@site.construction_type默认返回的是枚举的键名,要取你定义的显示值,直接通过枚举哈希查询即可。可以在模型中新增实例方法简化调用:
def humanized_construction_type return unless construction_type self.class.construction_types[construction_type] end
之后详情页的代码改为:
<li> <strong> <%= t(".construction_type") %> </strong> <%= @site.humanized_construction_type %> </li>
就能输出你期望的Brick/Block这类友好显示值。
内容的提问来源于stack exchange,提问作者Rachel
相关产品推荐
相关产品推荐

