2014-06-13 80 views
1

我試圖通過Categorizations模型將產品控制器中的關係設置爲ClothingSize模型。我得到「未經許可的參數:clothing_size」錯誤,並且此關係不會作爲結果。我認爲在視圖中的嵌套窗體有問題,因爲我無法得到「大小」字段出現,除非符號如下單獨顯示。我認爲這可能是另一個問題。與Rails 4中嵌套窗體的多對多關係 - 未經許可的參數錯誤

<%= form_for(@product) do |f| %> 
     <%= f.fields_for :clothing_size do |cs| %> 

模型

產品

class Product < ActiveRecord::Base 
    has_many :categorizations 
    has_many :clothing_sizes, through: :categorizations 
    accepts_nested_attributes_for :categorizations 
end 

分類已

class Categorization < ActiveRecord::Base 
    belongs_to :product 
    belongs_to :clothing_size 
    accepts_nested_attributes_for :clothing_size 
end 

ClothingSizes

class ClothingSize < ActiveRecord::Base 
    has_many :categorizations 
    has_many :products, through: :categorizations 
    accepts_nested_attributes_for :categorizations 
end 

控制器產品

def new 
    @product = Product.new 
    test = @product.categorizations.build 


    def product_params 
     params.require(:product).permit(:title, :description, :image_url, :image_url2, :price, :quantity, :color, :clothing_sizes => [:sizes, :clothing_size_id]) 
    end 
end 

查看

<%= form_for(@product) do |f| %> 
    <%= f.fields_for :clothing_size do |cs| %> 
    <div class="field"> 
     <%= cs.label :sizes, "Sizes" %><br> 
     <%= cs.text_field :sizes %> 
    </div> 
    <% end %> 
<% end %> 

回答

2

在你看來,你有:clothing_size(單數),但在你的product_params方法你有:clothing_sizes(複數)。因爲您的Product模型has_many :clothing_sizes,您希望它在您的視圖中是複數。

<%= form_for(@product) do |f| %> 
    <%= f.fields_for :clothing_sizes do |cs| %> 

此外,你會想建立一個clothing_size在控制器的product,並允許在你的product_params方法:clothing_sizes_attributes而非clothing大小。 (我想分離你的newproduct_params方法,使得product_params私人,但是這只是我。)

def new 
    @product = Product.new 
    @clothing_size = @product.clothing_sizes.build 
end 

private 
    def product_params 
    params.require(:product).permit(:title, :description, :image_url, :image_url2, :price, :quantity, :color, :clothing_sizes_attributes => [:sizes, :clothing_size_id]) 
    end 
+0

當我做在視圖clothing_size多場不顯示在頁面上的。我不知道爲什麼。這就是爲什麼它是單數。必須有其他的錯誤導致這種行爲。 – gjarnos

+0

它應該是複數,因爲關係是複數。沒有任何顯示的原因是因爲您需要爲您的'@ product'至少構建一個'clothing_size'。你可以在你的控制器中添加這個:'@ product.clothing_sizes.build'。 –

+0

這似乎讓我更進一步。大小現在顯示在窗體上。我現在得到了這個錯誤:'未經允許的參數:clothing_sizes_attributes' – gjarnos

相關問題