I have a many to many relationship between the two models (Region & Listing). I'm trying to use fields_for on the Listing form in order to multi-select Region's and have a Regionalization row created for each selected Region.
I can achieve the creation of the regionalization connection with a single input but am unable to get this working below for multi-select.
Any clue would be great. Thanks. I'm guessing I need to create a loop in the created method for each of the selected regions in the regionalization form.
Listing Model
has_many :regionalizations
has_many :regions, through: :regionalizations
accepts_nested_attributes_for :regionalizations
Region Model
has_many :regionalizations
has_many :listings, through: :regionalizations
Regionalization Model
belongs_to :region
belongs_to :listing
accepts_nested_attributes_for :region
Listing Controller
def new
@listing = Listing.new
@listing.regionalizations.build
end
def create
@listing = Listing.new(listing_params)
@listing.user_id = current_user.id
if @listing.save
redirect_to @listing, notice: "Your Listing was created successfuly"
else
render :new
end
end
def listing_params
params.require(:listing).permit(:name, :excerpt, :description, :email, :website, :phone_number, :user_id, :featured_image, :category_id, :regionalization_id,regionalizations_attributes: [:id, :region_id, :listing_id], regions_attributes: [:id, :name])
end
Listing Form
<%= form.fields_for :regionalizations do |regionalization_form| %>
<%= regionalization_form.collection_select(:region_id, Region.all, :id, :name, {multiple: true}, {class: 'form-control'}) %>
<% end %>
So after a bit of digging and the help of a very old vid from Ryan Bates & an updated version from Steve Polito I realised the solution. The setup above actually allowed me to add multiple regionalizations in my form. I just had to use the controller to loop through the build method.
This showed me I could add three regionalizations and they would be created independently on submission of the form. Once working,
I knew I needed to add the ability to destroy each form input and ultimately create some javascript to do this. Once I had this I knew I could add a new field also using Javascript and could remove the initial loop in the code above as the user now has the ability to add and destroy regionalization fields.
This link was a great help from steve and it's nice to see this way of doing it without using the gem 'cocoon' or similar for nested fields.
http://railscasts.com/episodes/196-nested-model-form-part-1
https://stevepolito.design/blog/create-a-nested-form-in-rails-from-scratch/
Steve provides a very clear solution for this and great scripts too & using with Rails 6 also. Thanks, everyone.
I hope this helps anyone that may come across it.