Frage

I have a multiselect (using bootstrap-multiselect) in my @minisets new form that aims to associate @scales with the @miniset via the @sizes table.

The associations work fine. What I'm stuck on is how to loop through the multiple :scale_id submissions from the multiselect and create lines in the @sizes table for them all.

Following this answer I have been trying to use split and then loop the create but I think the fact that that answer pertains to a HABTM relationship and mine is has_many_through means I need a different solution?

In my minisets controller I have

    def new
        @miniset = Miniset.new 
        @miniset.sizes.build
    end

    def create
        @miniset = Miniset.new(miniset_params)
        if @miniset.save
          params[:scale_id].split(',').each do |id|
            @miniset.sizes.create(params[:sizes_attributes])
        end
          redirect_to @miniset
        else
          render 'new'
        end
    end

private
    def miniset_params
      params.require(:miniset).permit(:name, :release_date, :material, :pcode, :notes, :quantity, :random, productions_attributes: [:id, :manufacturer_id, :miniset_id], sizes_attributes: [:id, :scale_id, :miniset_id], sculptings_attributes: [:id, :sculptor_id, :miniset_id])
    end
end

In my view I have

    <%= f.fields_for :sizes do |size_fields| %>
          <%= size_fields.label :scale_id, simple_pluralize(@miniset.scales.count, 'Scale') %>
         <%= size_fields.select :scale_id, 
                       options_from_collection_for_select(Scale.all, :id, :name, @miniset.scales.map(&:id)), 
                       {}, 
                       {class: 'multiselect', multiple: true} %>
    <% end %>

<script type="text/javascript">
      $(document).ready(function() {
        $('.multiselect').multiselect();
      });
    </script>

I'm currently getting error undefined methodsplit' for nil:NilClass` when I submit.

I think that may be because the log shows an empty scale_id passed before the two filled ones and split won't accept nil? Here is the log when submitting TWO scales.

Started POST "/minisets" for 127.0.0.1 at 2014-01-30 10:49:59 +0000
Processing by MinisetsController#create as HTML
  Parameters: {"utf8"=>"✓", "authenticity_token"=>"R0RxDMwB5/ytSb5qgjIlVR5as0/DTkstgFMDXcefDnc=", "miniset"=>{"name"=>"Test for size", "quantity"=>"10", "random"=>"0", "material"=>"Hard Plastic", "sizes_attributes"=>{"0"=>{"scale_id"=>["", "1", "5"]}}, "pcode"=>"", "release_date(1i)"=>"", "release_date(2i)"=>"", "release_date(3i)"=>"", "notes"=>""}, "Set Scale"=>{"#<ActiveRecord::Associations::CollectionProxy::ActiveRecord_Associations_CollectionProxy_Size:0x007fcf643c29f0>"=>""}, "commit"=>"Add set"}
  User Load (0.2ms)  SELECT "users".* FROM "users" WHERE "users"."remember_token" = 'd59f28d384d62b71719dd845b4e5353cdd993016' LIMIT 1
Unpermitted parameters: scale_id
  SQL (0.9ms)  INSERT INTO "minisets" ("created_at", "material", "name", "notes", "pcode", "quantity", "updated_at") VALUES (?, ?, ?, ?, ?, ?, ?)  [["created_at", Thu, 30 Jan 2014 10:49:59 UTC +00:00], ["material", "Hard Plastic"], ["name", "Test For Size"], ["notes", ""], ["pcode", ""], ["quantity", 10], ["updated_at", Thu, 30 Jan 2014 10:49:59 UTC +00:00]]
  SQL (0.6ms)  INSERT INTO "sizes" ("created_at", "miniset_id", "updated_at") VALUES (?, ?, ?)  [["created_at", Thu, 30 Jan 2014 10:49:59 UTC +00:00], ["miniset_id", 41], ["updated_at", Thu, 30 Jan 2014 10:49:59 UTC +00:00]]
   (4.2ms)  commit transaction
Completed 500 Internal Server Error in 153ms

NoMethodError (undefined method `split' for nil:NilClass):
  app/controllers/minisets_controller.rb:19:in `create'

I'm sure what I have after the split is incorrect but I can't play with it until the split works. I can get rid of the error by adding to_s before the split but I get no better results.

Been making very slow progress on this multiselect for days now so any help very much appreciated.

War es hilfreich?

Lösung

Thanks to this fantastic youtube video I solved my problem.

My form:

<%= f.fields_for(@size) do |sf| %>
      <%= sf.label simple_pluralize(@miniset.scales.count, 'Scale') %>

        <%= collection_select( :scales, :id, @all_scales, :id, :name, 
                   {}, 
                   {class: 'multiselect', multiple: true}) %>
<% end %>

In my minisets_controller I have the following new and create actions:

def new
    @miniset = Miniset.new 
    @all_scales = Scale.all
    @size = @miniset.sizes.build
end

  def create
    @miniset = Miniset.new(miniset_params)
    params[:scales][:id].each do |scale|
      if !scale.empty?
        @miniset.sizes.build(:scale_id => scale)
      end
    end
    if @miniset.save
      redirect_to @miniset
    else
      render 'new'
    end
  end

It works perfectly. If anyone else is having the same problem, trying to get multiselects to work in rails with has_many_through, I recommend watching that video. So pleased.

Lizenziert unter: CC-BY-SA mit Zuschreibung
Nicht verbunden mit StackOverflow
scroll top