(Rails)fields_for 序列化列未填充数据

(Rails) fields_for a serialized column are not being populated with data

我不会在 Rails 5.2 中通过 form_with 提交 @order@orderOrder class 的一个实例,它有一个用于地址字段的序列化列。地址字段由订单中的 fields_for 填写,当将表单提交给 OrdersController 时,所有字段/值都被正确传递。

问题是:如果 @order 验证失败,OrdersController 会再次呈现表单视图并出现 @order 的错误,但这里 fields_for 地址不是由 :address 散列填充。

我看到了很多将序列化列转换为 attr_accessors 的 hacky 解决方案。 是否有方便的解决方案来从 Rails 中的序列化列填充表单字段?

这是我的代码……

order.rb

class Order < ApplicationRecord
  serialize :address

  …

  validate  :address_validator

  …

  private

    def address_validator
      required_fields = [:firstname, :lastname, :line1, :city, :postal_code, :country]
      required_fields.each do |field|
        self.errors.add(:base, "Address / #{field.to_s.titleize} can't be blank") if self.address[field.to_s].blank?
      end
    end

    …
end

new.html.erb

<%= form_with model: @order, id: 'order-form', class: 'form', local: true do |f| %>
  <%= render 'shared/form_errors', object: f.object %>

  …

  <%= f.fields_for :address do |g| %>
    <%= render 'orders/address_fields', f: g %>
  <% end %>

  …

<% end %>

_address_fields.html.erb

<div class='form__row columns columns--responsive-to-small columns--with-gutter'>
  <div class='form__input form__input--mandatory'>
    <%= f.label :firstname, 'Firstname' %>
    <%= f.text_field :firstname %>
  </div>

  <div class='form__input form__input--mandatory'>
    <%= f.label :lastname, 'Lastname' %>
    <%= f.text_field :lastname %>
  </div>
</div>

<div class='form__row'>
  <div class='form__input form__input--mandatory'>
    <%= f.label :line1, 'Address (line 1)' %>
    <%= f.text_field :line1 %>
  </div>
</div>

…

提交表单后,@order 对象具有以下值(存在地址值)

(byebug) @order
#<Order id: nil, order_id: "HvMB00KS-73e1fc", …, created_at: nil, updated_at: nil, address: {"firstname"=>"Rocky", "lastname"=>"Marciano", "line1"=>"Saplestreet 123", "line2"=>"", "city"=>"Clashtown", "postal_code"=>"18726", "country"=>"Germany"}, email: "test@mail.com", products: … >

谢谢!

Nando Vieira 提出了一个名为 store_accessor that can be used together with a serialized attributes hash in order to create accessors for its keys. I found this thanks to Using PostgreSQL and jsonb with Ruby on Rails 的方便(没有详细记录)的解决方案。

使用上面的示例地址哈希,我们可以定义……

class Order < ApplicationRecord
  serialize :address
  store_accessor :address, :firstname, :lastname, :postal_code, …
  …
end

设置和读取地址的属性,例如……

order = Order.new
order.firstame = 'Billy'
order.firstname
#=> "Billy"
order.address['firstname']
#=> "Billy"

在@order 的表单中,可以直接设置 address 的键,表单将分别填充……

<%= form_with model: @order, local: true do |f| %>

  <%= f.label :firstname, 'Firstname' %>
  <%= f.text_field :firstname %>

  <%= f.label :lastname, 'Lastname' %>
  <%= f.text_field :lastname %>

<% end %>

在 OrdersController 中使用强大的参数,例如……

params.require(:order).permit(:firstname, :lastname)