我在两个模型(区域和列表)之间有多对多的关系。我正在尝试在列表表单上使用 fields_for 以多选区域并为每个选定区域创建区域化行。
我可以通过单个输入实现区域化连接的创建,但无法在下面进行多选操作。
任何线索都会很棒。谢谢。我猜我需要在 created 方法中为区域化表单中的每个选定区域创建一个循环。
上市模式
has_many :regionalizations
has_many :regions, through: :regionalizations
accepts_nested_attributes_for :regionalizations
区域模型
has_many :regionalizations
has_many :listings, through: :regionalizations
区域化模型
belongs_to :region
belongs_to :listing
accepts_nested_attributes_for :region
上市控制器
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
上市表格
<%= form.fields_for :regionalizations do |regionalization_form| %>
<%= regionalization_form.collection_select(:region_id, Region.all, :id, :name, {multiple: true}, {class: 'form-control'}) %>
<% end %>