Search code examples
ruby-on-railscheckboxdevisesimple-form-for

Rails Simple_Form Multiple Select Checkboxes


I'm new to Rails, and I'm having some issues with Simple_Form, Devise and checkboxes.

I have added some additional columns to my Devise model, including a column where I would like users to tick one-or-more checkboxes. Similar to this:

Areas of Operation: [ ] England [ ] Wales [ ] Scotland

Everything is fine, but when I select multiple areas, then save, the selections do not save to the database.


Here's my View code [app/views/devise/registrations/edit.html.erb]:

<%= simple_form_for(resource, html: { class: 'form-horizontal'}, :as => resource_name, :url => registration_path(resource_name), :html => { :method => :put }) do |f| %>

<%= f.input :areas, :as => :check_boxes, :collection => ["England", "Wales", "Scotland", "Northern Ireland"] %>

<% end %>

And here's my ApplicationController code [app/controllers/application_controller.rb]:

class ApplicationController < ActionController::Base
protect_from_forgery with: :exception

before_filter :configure_permitted_parameters, if: :devise_controller?

protected

 def configure_permitted_parameters
  devise_parameter_sanitizer.for(:sign_up) << :areas
  devise_parameter_sanitizer.for(:account_update) << :areas
 end
end

I'm sure I am missing something obvious, but I've been Googling for hours with no luck.

Any help would be greatly appreciated!


EDIT:

Apologies. Here is the scheme for the Devise (actually named 'providers') table:

create_table "providers", force: true do |t|
  t.string   "email",                  default: "", null: false
  t.string   "encrypted_password",     default: "", null: false
  t.string   "reset_password_token"
  t.datetime "reset_password_sent_at"
  t.datetime "remember_created_at"
  t.integer  "sign_in_count",          default: 0,  null: false
  t.datetime "current_sign_in_at"
  t.datetime "last_sign_in_at"
  t.string   "current_sign_in_ip"
  t.string   "last_sign_in_ip"
  t.datetime "created_at"
  t.datetime "updated_at"
  t.string   "first_name"
  t.string   "last_name"
  t.string   "organisation"
  t.string   "street"
  t.string   "city"
  t.string   "county"
  t.string   "postcode"
  t.string   "areas"
  t.string   "methods"
end

add_index "providers", ["email"], name: "index_providers_on_email", unique: true
add_index "providers", ["reset_password_token"], name: "index_providers_on_reset_password_token", unique: true

Solution

  • There are many ways to save areas,

    1) Best way is to create new model called area and have many-to-many associations with user. check. This is basic app where user has many projects ascociations.

    2) If you dont want to create separate area model then you can store area in one of column user's. Either you can serialize the column. Here you can store data in arr or hash form

    3) Add before filter in user and before saving the user, join the areas and save it as string.