All threads / How to add records to has_many :through association

Ask A Question

Notifications

You’re not receiving notifications from this thread.

How to add records to has_many :through association

Wesly Mezarina asked in Rails

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.

Join the discussion

Want to stay up-to-date with Ruby on Rails?

Join 33,665+ developers who get early access to new tutorials, screencasts, articles, and more.

    We care about the protection of your data. Read our Privacy Policy.

    logo Created with Sketch.

    Ruby on Rails tutorials, guides, and screencasts for web developers learning Ruby, Rails, Javascript, Turbolinks, Stimulus.js, Vue.js, and more. Icons by Icons8

    © 2020 GoRails, LLC. All rights reserved.