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
是茅塞頓開感謝。 – akhanaton