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 %>