Search code examples
ruby-on-railsruby-on-rails-4form-helpers

Formhelpers Checked=checked/Selected=selected when editting


I've got two situations when I use all of the available objects in which the user can choose.

The first situation is a user can choose 1 pictogram out of the whole list for an activity.

The second situation is where a user can choose multiple clients for an activity.

In both cases I can't manage to keep those saved to be checked/selected when I try to edit the activity. Is there a way to do this?

   <div class="pictograms">
      <% for p in Pictogram.all  %>
        <%= radio_button_tag "activity[pictogram_id]", p.id %>
        <%= label_tag(:pictogram_id, image_tag(p.url, :width => "75")) %>
      <% end %>
  </div>
  <div class="clients">
    <% for client in Client.all %>
      <label class="activity">
        <%= check_box_tag "activity[client_ids][]", client.id %>
        <%= client.name %>
      </label>
    <% end %>
  </div>

Solution

  • You can write helper method that returns true, false for both of the cases.

    view:
    <% for p in Pictogram.all  %>
      <%= radio_button_tag "activity[pictogram_id]", p.id, pictogram_is_true?(p) %>
    <% end %>
    
    <% for client in Client.all %>
        <%= check_box_tag "activity[client_ids][]", client.id, client_is_true?(client) %>
    <% end %>
    
    helper:
    def pictogram_is_true?(p)
      // query here and return true or false
    end
    
    def client_is_true?(client)
      // query here and return true or false
    end