Skip to main content

How to add records to has_many :through association

Rails • Asked by Wesly Mezarina

I have three models called Site, Model and ModelSite as shown below. If i create a new model_site i can choose a site and model to save which works good but what i need help in is how can i choose a site or model if I'm creating a new site or model? I'm showing an example on how i create a new site which has a .association :sites input. I can pick the sites but it does not get saved.

class Site < ActiveRecord::Base
  has_many :model_sites, inverse_of: :site, dependent: :destroy
  has_many :models, through: :model_sites
end

class ModelSite < ActiveRecord::Base
 belongs_to :model
 belongs_to :site
 validates_presence_of :model, :site
end

class Model < ActiveRecord::Base
 has_many :model_sites, inverse_of: :model, dependent: :destroy
 has_many :sites, through: :model_sites
end

New site

<%= simple_form_for [:admin, @model] do |f| %>
 <%= f.input :name %>
 <%= f.association :sites, as: :check_boxes %>
<% end %>

Something like this may work?

<%= f.label :name %>
<%= f.collection_check_boxes(:site_ids, Sites.all, :id, :name) %>

Plus another way on Stack Overflow:

http://stackoverflow.com/questions/5054633/rails-3-has-many-through-form-with-checkboxes


I did try that and it still does not save. I'm assigning the site_id and model_id which has to be saved by creating a new ModelSite. I need to find a way to save those id's when creating a new site or model.


Hey Wesley,

So you said that this is a form for a new Site? A site has_many models, not many sites. Should your form be for association :sites instead?


+1 on what Chris said. Also, it should not cause any conflicts but out of curiosity why did you choose Model as a Model name? Not criticism, just curious.


I do have it as that Chris but i guess i actually cant save it through a model or site i have to create it through the model_site Model.

I could have called my Model girl instead of model to not confuse anything but having the word Model just sounded better to me.


Login or Create An Account to join the conversation.

Subscribe to the newsletter

Join 27,623+ developers who get early access to new screencasts, articles, guides, updates, and more.

    By clicking this button, you agree to the GoRails Terms of Service and Privacy Policy.

    More of a social being? We're also on Twitter and YouTube.