Skip to content

Instantly share code, notes, and snippets.

@DiegoSalazar
Last active December 28, 2015 10:59
Show Gist options
  • Star 0 You must be signed in to star a gist
  • Fork 0 You must be signed in to fork a gist
  • Save DiegoSalazar/7490062 to your computer and use it in GitHub Desktop.
Save DiegoSalazar/7490062 to your computer and use it in GitHub Desktop.
Using a drop down to add a relationship between has_many :through models.
# models
class Genotype < ActiveRecord::Base
has_many :genotypes_colors
has_many :colors, through: :genotypes_colors
# to post nested attributes in a form using fields_for
accepts_nested_attributes_for :genotypes_colors
# if you're using Rails 3 attr_accessible
attr_accessible :genotypes_colors_attributes, ...rest of accessible attribs
end
class GenotypesColor < ActiveRecord::Base
belongs_to :genotype
belongs_to :color
end
class Color < ActiveRecord::Base
has_many :genotypes_colors
has_many :genotypes, through: :genotypes_colors
end
# controller
class GenotypesController < ApplicationController
def edit
@genotype = Genotype.find params[:id]
@colors = Color.all
end
def update
@genotype = Genotype.find params[:id]
if @genotype.update! genotype_params # or params[:genotype] if you're not using Rails 4 Strong Parameters
# success, the genotypes_colors aassociation should now be created and now you can access @genotype.colors
else
# oh noes
end
end
private
# if you're using Rails 4 Strong Parameters
def genotype_params
params.require(:genotype).permit(genotypes_colors_attributes: [:color_id], ...rest of genotype attribs)
end
end
# edit view
<%= form_for @genotype do |f| %>
<%= select_tag 'genotype[genotypes_colors_attributes][][color_id]', options_from_collection_from_select(@colors, 'id', 'angora_color') %>
.. rest of code ...
<% end %>
@DiegoSalazar
Copy link
Author

The idea is to generate a drop down for all colors you want to assign to a genotype. Then assign the color's id to the color_id attribute of the genotypes_colors association by simply selecting it from the dropdown. Then assign those params in the controller to the genotype.

Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment