Skip to content

Instantly share code, notes, and snippets.

@anitagraham
Last active January 28, 2018 20:11
Show Gist options
  • Star 1 You must be signed in to star a gist
  • Fork 0 You must be signed in to fork a gist
  • Save anitagraham/5acc1453b6dd8fe97589dca2b723036e to your computer and use it in GitHub Desktop.
Save anitagraham/5acc1453b6dd8fe97589dca2b723036e to your computer and use it in GitHub Desktop.
rails has_many_through with checkboxes
# extract from photo.rb
# after the first two has_manys, the rest are needed for STI, a component can be a base, capital, shaft, column or letterbox
belongs_to :product
belongs_to :page, :inverse_of => :photos, :foreign_key => 'page_id'
has_many :assignments
has_many :components, :through => :assignments
has_many :bases, :through => :assignments, :foreign_key=>'component_id'
has_many :shafts, :through => :assignments, :foreign_key=>'component_id'
has_many :capitals, :through => :assignments, :foreign_key=>'component_id'
has_many :columns, :through => :assignments, :foreign_key=>'component_id'
has_many :letterboxes, :through => :assignments, :foreign_key=>'component_id'
before_destroy {|photo| photo.components.clear}
<!-- A photo shows several components (which have been put together) -->
<!-- A series is a product line, and all the components in a series are compatible with each other -->
<!-- When setting up, the user selects which Series is shown in a photo, then selects the exact components shown in the photo. -->
<!-- Components are divided into several types (using STI) so when displaying them we set up a set of checkbox for each component_type-->
<!-- Found it hard to use 'series' as a singular model name, and what is the plural anyway, so settled for 'product' instead -->
<!-- If you ignore all the fussing around with comp_type_name etc, the real work is done at line 24 with f.collection_checkboxes -->
<!-- show a set of components for a series selected for a photo -->
<!-- series=product, photo -->
<div id="selectComponents"
<%= simple_fields_for :photo do |f| %>
<h1>Select <%= series.name%> Components</h1>
<% Refinery::Caststone::Component::COMP_TYPES.each do |comp_type|
comp_type_name=comp_type.pluralize
comp_type_method = comp_type_name.downcase
comp_ids = "#{comp_type}_ids".downcase
if series.send(comp_type_method).any? %>
<fieldset id="<%= comp_type%>" class="component_type">
<legend>
<%= comp_type%>
</legend>
<%= f.collection_check_boxes comp_ids, series.send(comp_type_method), :id, :name %>
<%= link_to "Clear #{comp_type_name}", '#', :id => comp_type_name, :class=> 'button clearRadioSet'%>
</fieldset>
<%end%>
<%end%>
<a id="redraw_button" class="button" href="#" tooltip="Redraw with the currently selected components ">Redraw</a>
<%end%>
</div>
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment