samedi 7 janvier 2017

Rails Form Check Box Array value

I'm maintaining a Rails 3.2.22.5 legacy app and creating a form to send messages internally to users (in this case they are called medics). Here is what my form currently looks like.

<%= form_for(@mass_message, url: '/mass_messaging', method: 'post') do |f| %>
  <%= f.text_field :subject, placeholder: "Subject" %>
  <%= f.text_area :body, placeholder: "Body of message"%>
  <%= f.label :medic %>
  <%= f.select(:medic_ids, medic_select,  {}, {:multiple => true, :class => 'select'}) %>
  <%= f.button "Submit" %>

<% end %>

This works fine but I'd like to be able to shovel groups of Medics by a division column into the medic_ids array on the object.

From the console when I do the following:

m = MassMessage.new
m.medic_ids = Medic.where(division: "Dallas").map {|medic| medic.id}
m.save

It will get the ids that are mapped from the where clause and inject them into the medic_ids array properly and create the record in a join table called MassMessageMedic properly.

However, in this form I need the ability to create some sort of selector or even checkboxes in the form to select the different divisions of which there are 4. So this is a two part question really

1.) Given these four statements (divisions)

Medic.where(division: "Dallas").map {|medic| medic.id}
Medic.where(division: "Houston").map {|medic| medic.id}
Medic.where(division: "Beaumont").map {|medic| medic.id}
Medic.where(division: "Texoma").map {|medic| medic.id}

How can I construct these into some sort of helper method that would allow each array to be selected (one or multiple) and injected into the medic_ids array? I'm trying different things and thinking a helper method called medic_select might be the answer but I'm hitting a wall with how to create this selector which will essentially be an array of arrays if I'm not mistaken.

2.) Given the above arrays how could I instead of a selector in the form use a check_box to define that when the checkbox is clicked the proper medics are selected by division. Here is an example I tried but I'm receiving an error:

  <%= f.label :houston %>
  <%= f.check_box :medic_ids, Medic.where(division: "Houston").map {|medic| medic.id} %>
  <%= f.label :dallas %>
  <%= f.check_box :medic_ids, Medic.where(division: "Dallas").map {|medic| medic.id} %>

The error I receive is: undefined methodmerge' for #` when trying to do it this way.

I'm pretty sure this can be done, but after an hour of searching and trying different things I'm really no further than when I began.

I'm hoping someone can point me in the right direction on this one.

In the meantime I will continue to Google and research Stack to see if someone else had a similar issue.

If my code and/or question is not concise or clear please let me know and I will edit.

Aucun commentaire:

Enregistrer un commentaire