mercredi 25 mai 2016

Populating checkboxes based on db in Rails 4

I'm working on this reconciliation system where users can choose which fields they would like to use when importing records. I finally got the select to pre-populate with the correct info but can't for the life of me get the checkboxes to do the same. Here's my form:

    #views/match_rule/edit.html.erb

    <%= form_for(@match_rules) do |f| %>
    <%= f.label :name, "Name" %>
    <%= f.text_field :name, placeholder: "Rule Set Name" %>
    <%= f.label :algorithm, "Choose an algorithm" %>
    <%= f.select :algorithm, build_algorithm_select_options %>
    <%= f.label :match_fields, "Available fields" %>
    <% @field_options.each do |field| %>
      <%= f.check_box :match_fields %>
      <%= f.label :match_fields, "#{field.last}" %><br/>
    <% end %>
    <%= f.submit "Save", class: "button primary" %>
    <%= link_to "Cancel", match_rule_index_path, class: "button" %>
  <% end %>

Currently the corresponding controller is simply building a hash of fields so not to clutter up the view with repetitive code

  #controllers/match_rule_controller.rb

  def edit
    @field_options = {
      name: "Name",
      email: "Email",
      phone: "Phone Number",
      gender: "Gender",
      marital_status: "Marital Status",
      dob: "Date of Birth",
      campus: "Campus",
      address: "Street Address",
      city: "City",
      state: "State",
      zip: "Zip"
    }
  end

My model is serializing the fields

#models/match_rule.rb

class MatchRule < ActiveRecord::Base
  has_many :inboxes
  enum algorithm: [ :adjustable, :classic_minimal, :classic_standard ]
  serialize :match_fields
end

and my database fields are storing all the options that should populate the checkboxes in the match_fields column screenshot of the db structure

If it helps to see how I seeded the db with an array here's that:

#db/seeds.rb

classic_minimal = MatchRule.create(algorithm: 'classic_minimal', match_fields: ['name', 'email', 'phone', 'gender', 'zip'], name: 'Classic Minimal')
classic_standard = MatchRule.create(algorithm: 'classic_standard', match_fields: ['name', 'email', 'phone', 'gender', 'marital_status', 'dob', 'campus', 'address', 'city', 'state', 'zip'], name: 'Classic Standard')
adjustable = MatchRule.create(algorithm: 'adjustable', match_fields: ['name', 'phone', 'campus', 'marital_status', 'zip'], name: 'Adjustable')

I've checked out similar questions on here, the one closest to helping me have a breakthrough was the answer to this question: Set checkboxes on edit method in Rails 4 where he says to use .include? to determine the checked status, but I'm not sure what I would put in the params because I need to parse through the hash inside match_fields for each and every field and that would get pretty gnarly.

Any advice or guidance is greatly appreciated, thanks!




Aucun commentaire:

Enregistrer un commentaire