Question

I have a application that allows a user to upload a creative and assign it to multiple weeks

Week Model

  class Week < ActiveRecord::Base

    has_many :creative_weeks
    has_many :creatives, :through => :creative_weeks

  end

Creative Model

  class Creative < ActiveRecord::Base

    has_many :creative_weeks
    has_many :weeks, :through => :creative_weeks

    mount_uploader :image, CreativeUploader

 end  

Creative Weeks [Join Table]

  class CreativeWeek < ActiveRecord::Base
    belongs_to :week
    belongs_to :creative
  end 

I know the association works which allows me to issue a creative to multiple weeks based on my console:

 2.0.0p353 :020 > c = Creative.first
   Creative Load (0.2ms)  SELECT "creatives".* FROM "creatives" ORDER BY "creatives"."id" ASC LIMIT 1
    => #<Creative id: 10, name: "", account_id: 1, week_id: nil, campaign_id: 1, image:       "Quakes_2013_DigiOOH_40YR_704x496.jpg", created_at: "2014-02-20 18:13:47", u
    pdated_at: "2014-02-20 18:13:47"> 
 2.0.0p353 :021 > c.week_ids
    (0.2ms)  SELECT "weeks".id FROM "weeks" INNER JOIN "creative_weeks" ON "weeks"."id" =    "creative_weeks"."week_id" WHERE "creative_weeks"."creative_id" = ?  [["
    creative_id", 10]]
    => [3] 
2.0.0p353 :022 > c.week_ids = [1, 2, 3]
   Week Load (0.2ms)  SELECT "weeks".* FROM "weeks" WHERE "weeks"."id" IN (1, 2, 3)
   Week Load (0.1ms)  SELECT "weeks".* FROM "weeks" INNER JOIN "creative_weeks" ON "weeks"."id" = "creative_weeks"."week_id" WHERE "creative_weeks"."creative_id" 
   = ?  [["creative_id", 10]]
(0.1ms)  begin transaction
SQL (0.3ms)  INSERT INTO "creative_weeks" ("created_at", "creative_id", "updated_at", "week_id")  VALUES (?, ?, ?, ?)  [["created_at", Thu, 20 Feb 2014 18:20:27
UTC +00:00], ["creative_id", 10], ["updated_at", Thu, 20 Feb 2014 18:20:27 UTC +00:00],   ["week_id", 1]]
SQL (0.1ms)  INSERT INTO "creative_weeks" ("created_at", "creative_id", "updated_at", "week_id")    VALUES (?, ?, ?, ?)  [["created_at", Thu, 20 Feb 2014 18:20:27
UTC +00:00], ["creative_id", 10], ["updated_at", Thu, 20 Feb 2014 18:20:27 UTC +00:00],   ["week_id", 2]]
(1.0ms)  commit transaction
  => [1, 2, 3] 
2.0.0p353 :023 > 

The issue I am having is getting this same functionality to work on the front end. It will only pass in one value, typically the last one chosen

In my form:

<div class="field">
<%= f.collection_select(:week_ids, Week.all, :id, :start_at, {}, multiple: true, name: 'creative[week_ids]') %>
</div> 

Can anyone advise me what I am missing?

TIA

Was it helpful?

Solution

Change the select tag's name to this:

name: 'creative[week_ids][]'

That extra '[]' at the end of the name specifies that you want an array of values to be posted.

Using strong parameters you have to specify that the value will be an array:

def your_strong_params
  params.require(:creative).permit(week_ids: [])
end
Licensed under: CC-BY-SA with attribution
Not affiliated with StackOverflow
scroll top