2014-02-20 65 views
0

我有一個應用程序,允許用戶上傳的廣告,並將其分配給多個星期多選不傳遞多個值

周型號

class Week < ActiveRecord::Base 

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

    end 

創新模式

class Creative < ActiveRecord::Base 

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

    mount_uploader :image, CreativeUploader 

end 

創意周[加入表]

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

我知道該協會合作,讓我根據我的控制檯上發出的創意,以多個星期:

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 > 

我有越來越此相同的功能,以在前面的工作問題結束。它只能傳遞一個值,通常是最後一個選擇

在我的形式:

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

誰能告訴我,我缺少的是什麼?

TIA

回答

1

改變的選擇標籤的名稱是:

name: 'creative[week_ids][]' 

這額外的「[]」在名稱末尾指定要值數組被張貼。

使用你有強大的參數指定的值將是一個數組:

def your_strong_params 
    params.require(:creative).permit(week_ids: []) 
end 
+0

不幸的是我已經試過了。當我添加額外括號時,它不會允許發佈任何記錄。我正在使用Rails 4,並且在許可部分中目前有:week_ids。你認爲我必須在那裏做更多的事情來讓陣列通過嗎? – RubyNewbie

+0

添加到答案。 – DiegoSalazar

+0

現貨!知道這是阻止多條記錄提交。謝謝! – RubyNewbie