How to edit a Rails serialized field in a form?

后端 未结 8 640
-上瘾入骨i
-上瘾入骨i 2020-12-04 07:16

I have a data model in my Rails project that has a serialized field:

class Widget < ActiveRecord::Base
  serialize :options
end

The opti

8条回答
  •  有刺的猬
    2020-12-04 08:11

    I was facing the same issue, after some research i found a solution using Rails' store_accessor to make keys of a serialized column accessible as attributes.

    With this we can access "nested" attributes of a serialized column …

    # post.rb
    class Post < ApplicationRecord
      serialize :options
      store_accessor :options, :value1, :value2, :value3
    end
    
    # set / get values
    post = Post.new
    post.value1 = "foo"
    post.value1
    #=> "foo"
    post.options['value1']
    #=> "foo"
    
    # strong parameters in posts_controller.rb
    params.require(:post).permit(:value1, :value2, :value3)
    
    # form.html.erb
    <%= form_with model: @post, local: true do |f| %>
      <%= f.label :value1 %>
      <%= f.text_field :value1 %>
      # …
    <% end %>
    

提交回复
热议问题