我正在尝试更新产品,请参阅下面的代码。我似乎无法更新类别。欢迎任何帮助。
产品型号:
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