哈希被保存到数据库但无法在 Rails 表单中呈现其值?

Posted

技术标签:

【中文标题】哈希被保存到数据库但无法在 Rails 表单中呈现其值?【英文标题】:Hash being saved to database but unable to render its values in Rails forms? 【发布时间】:2021-09-06 06:02:03 【问题描述】:

我向模型Plan 添加了一个新列,名为:per_unit_quantities_configuration,它是一个包含minmaxstep 键/值的哈希。

t.jsonb "per_unit_quantities_configuration", default: 

当我编辑计划时,哈希值已正确保存到数据库(我可以从控制台访问每个键/值),但表单未显示其任何值(字段为空)。

我尝试为Plan 模型中的列添加store_accessor,但它不起作用:

store_accessor :per_unit_quantities_configuration, :min, :max, :step

不显示哈希值的 simple_form html 示例:

<%= simple_form_for [:admin, @base_plan, @plan] do |f| %>
    <% if f.object.base_plan.per_unit? %>
    <div class="d-flex">
      <%= f.simple_fields_for :per_unit_quantities_configuration do |fields| %>
        <% if f.object.errors[:per_unit_quantities_configuration].any? %>
          <%= f.error :per_unit_quantities_configuration, id: "per_unit_price_error", class: "invalid-feedback", error_prefix: "gato" %>
        <% end %>
        <%= fields.input :min %>
        <%= fields.input :max %>
        <%= fields.input :step %>

      <% end %>
    </div>
  <% end %>
  <%= f.button :submit, class: "pull-right" %>
<% end %>

我做错了什么?

【问题讨论】:

我认为不需要在 per_unit_quantities_configuration 字段中包装 3 个输入 min, max, step,因为它是 store_accessor,我们可以像普通字段一样访问它的属性 @LamPhan 谢谢。我按照你的建议做了,现在表单正在显示哈希值,但没有保存更改。更新后我被重定向到正确的视图(提示没有验证错误),但更改没有保留。 你如何permit 这些值(在控制器上)? @LamPhan 这是我去看的第一件事,但我看不出有什么问题:def plan_params params.require(:plan).permit( per_unit_quantities_configuration: %i(min max step), ) end 【参考方案1】:

既然你设置了store_accessor :per_unit_quantities_configuration,那么你可以直接访问min, max, step的3个属性,这样你就不需要在simple_fields_for :per_unit_quantities_configuration上包装这些属性并将它们视为普通字段(这意味着在控制器上你必须permit它们作为普通字段)

# view
<%= f.input :min %>
<%= f.input :max %>
<%= f.input :step %>

# controller
def plan_params     
 params.require(:plan).permit(:min,:max,:step)   
end

【讨论】:

谢谢你,这个字眼!

以上是关于哈希被保存到数据库但无法在 Rails 表单中呈现其值?的主要内容,如果未能解决你的问题,请参考以下文章

Rails 4 表单数据保存为 Nil

从rails中的控制器渲染部分

Django:表单未保存到数据库

Rails 4. 如何将authentity_token 添加到通过部分呈现的表单中?

数据库保存问题 Vue.js 和 Rails

Rails - 相同的模型/控制器,但不同的视图