2015-04-29 101 views
0

我正在嘗試更新產品,請參閱下面的代碼。我似乎無法更新類別。歡迎任何幫助。ActiveRecord嵌套值更新失敗

產品型號:

class Product < ActiveRecord::Base 
    belongs_to :category 

    accepts_nested_attributes_for :category 

    def category_name 
    category.try(:name) 
    end 

    def category_name=(name) 
    Category.find_or_create_by(name: name) if name.present? 
    end 
end 

分類模型:

class Category < ActiveRecord::Base 
    has_many :products 
end 

產品控制器:

class ProductsController < ApplicationController 
    def index 
    @products = Product.all 
    end 

    def show 
    @product = Product.find(params[:id]) 
    end 

    def edit 
    @product = Product.find(params[:id]) 
    end 

    def update 
    @product = Product.find(params[:id]) 
    @product.update(products_params) 
    redirect_to @product 
    end 

    private 

    def products_params 
    products_params = params.require(:product).permit(:name, :category_id, category_attributes: [:category_name]) 
    end 
end 

回答

1

您所創建的產品類中的二傳手,但你傳遞的屬性爲嵌套模型。您應該選擇其中一種解決方案。最好的之一是在rails中委託nester屬性處理。

http://api.rubyonrails.org/classes/ActiveRecord/NestedAttributes/ClassMethods.html

class Product < ActiveRecord::Base 
    belongs_to :category 
    accepts_nested_attributes_for :category 
end 

class Category < ActiveRecord::Base 
    has_many :products 
end 

class ProductsController < ApplicationController 
    def index 
    @products = Product.all 
    end 

    def show 
    @product = Product.find(params[:id]) 
    end 

    def edit 
    @product = Product.find(params[:id]) 
    end 

    def update 
    @product = Product.find(params[:id]) 
    @product.update(products_params) 
    redirect_to @product 
    end 

    private 

    def products_params 
    params.require(:product).permit(:name, category_attributes: [:name]) 
    end 
end 
+0

是茅塞頓開感謝。 – akhanaton