4
3

Delete article

Deleted articles cannot be recovered.

Draft of this article would be also deleted.

Are you sure you want to delete this article?

More than 5 years have passed since last update.

ARのserializeにfields_forの値を突っ込む

Posted at

ActiveRecordのserializeメソッドでカラムにシリアライズした値をDBに保存できるが、fields_forを使ってネストしたデータを保存してみる。

とりあえず保存

モデルはこんな感じで

user.rb
class User < ActiveRecord::Base
  serialize :other, Hash 
end

viewはこんな感じ

_form.html.slim
= form_for @user do |f|
  div
    = f.text_field :name
  div
    = f.fields_for :other do |ff|
      = ff.text_field :hoge
      = ff.text_field :fuga
  div
    = f.submit

とりあえず保存すると以下みたいになる。

User.last.other => {"hoge"=>"222", "fuga"=>"3333"}

だけどもこのままだと編集とか仕様とするとother内容がフォームに反映できない

編集時に反映できるようにする

fields_forの第2引数にOpenStructのインスタンスを渡す。Hash渡すとfields_forメソッド内でfields_options扱いになる

_form.html.slim
= form_for @user do |f|
  div
    = f.text_field :name
  div
    = f.fields_for :other, OpenStruct.new(f.object.other) do |ff|
      = ff.text_field :hoge                   
      = ff.text_field :fuga
  div
    = f.submit

これで編集時にもフォームに値が反映されている
用途的にそんなに無いかもしれないが。。。

4
3
0

Register as a new user and use Qiita more conveniently

  1. You get articles that match your needs
  2. You can efficiently read back useful information
  3. You can use dark theme
What you can do with signing up
4
3

Delete article

Deleted articles cannot be recovered.

Draft of this article would be also deleted.

Are you sure you want to delete this article?