Welcome to ShenZhenJia Knowledge Sharing Community for programmer and developer-Open, Learning and Share
menu search
person
Welcome To Ask or Share your Answers For Others

Categories

I use Rails 6.1 and the gem simple_form. I want save value of multiple checkbox in an object (string serialized or array). i don't find a simple solution.

table

    class CreateSpots < ActiveRecord::Migration[6.0]
  def change
    create_table :spots do |t|

      t.string :wind_direction

      t.timestamps
    end
  end
end

_form.html.erb

<%= simple_form_for (spot) do |f| %> 
  <%= f.input :wind_direction, as: :check_boxes, collection: Spot::DIRECTION %>
  <%= f.submit %>
<% end %>

model

  class Spot < ApplicationRecord
  DIRECTION = ['N','NW','W','SW','S','SE','E','NE']
  end

After submit the form, the output of wind_direction is Nil

ideally, i look for a string, i work with this format actually.

wind_direction: "["W", "NW", "N", "NE", "E"]",

Thanks for any suggestions


与恶龙缠斗过久,自身亦成为恶龙;凝视深渊过久,深渊将回以凝视…
thumb_up_alt 0 like thumb_down_alt 0 dislike
410 views
Welcome To Ask or Share your Answers For Others

1 Answer

i've find a solution, i've create a join table like in this example. It seem a reliable way to handle check-box

https://www.sitepoint.com/save-multiple-checkbox-values-database-rails/

and i serialize the result with .to_json


与恶龙缠斗过久,自身亦成为恶龙;凝视深渊过久,深渊将回以凝视…
thumb_up_alt 0 like thumb_down_alt 0 dislike
Welcome to ShenZhenJia Knowledge Sharing Community for programmer and developer-Open, Learning and Share
...