表格不保存外键

时间:2014-05-01 19:41:14

标签: ruby-on-rails ruby-on-rails-4

我正在尝试创建一个Product,它具有Category模型的外键,但由于某种原因,外键永远不会保存到数据库中。

这是我的表格

<%= nested_form_for @product do |f| %>
<div>
    <%= f.label :category %><br>
    <%= f.select :category_id, Category.all.map{ |s| [s.name, s.id]}, :include_blank => true %>
</div>
<div>
    <%= f.label :name %><br>
    <%= f.text_field :name %><br>
</div>
<div>
    <%= f.label :price %><br>
    <%= f.number_field :price %><br>
</div>
<div>
    <%= f.label :description %><br>
    <%= f.text_area :description %><br>
</div>

    <%= f.submit %>
<% end %>

和控制器

class Admin::ProductsController < AdminController

  def index
    @products = Product.all
  end

  def new
    @product = Product.new
  end

  def create
    @product = Product.new(product_params)
    if @product.save
        flash[:notice] = "You have added #{@product.name}"
        redirect_to admin_products_path
    else
        flash[:error] = "An error occured"
        render "new" 
    end     
  end

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

  def update
    @product = Product.find(params[:id])
    if @product.update(product_params)
      flash[:notice] = "Succesfully updated #{@product[:name].titleize}"
      redirect_to admin_products_path
    else
      flash[:error] = "An error occred update #{@product[:name].titleize}"
      render "edit"
    end
  end

  def destroy
    @product = Product.find(params[:id])
    if @product.destroy
      flash[:notice] = "You succesfully removed #{@product.name}"      
    else 
      flash[:error] = "An error occured trying to remove #{@product.name}"
    end
    redirect_to admin_products_path
  end

  private

    def product_params
            params.require(:product).permit(:name, :price, :category_id, :description,
        stocks_attributes: [ :id, :size, :amount, :_destroy ])
        end

end

服务器日志:

Processing by ProductsController#create as HTML
  Parameters: {"utf8"=>"✓", "authenticity_token"=>"+rHOeT8GvAB4zF5QjR1RLJiFyh38d+bgwgA4KS6Fiz8=", "product"=>{"category_id"=>"1", "name"=>"awfsdsd", "price"=>"111", "description"=>"adasdada"}, "commit"=>"Create Product"}
  Admin Load (0.3ms)  SELECT  "admins".* FROM "admins"  WHERE "admins"."id" = 1  ORDER BY "admins"."id" ASC LIMIT 1
Unpermitted parameters: category_id
   (0.1ms)  BEGIN
   (0.2ms)  ROLLBACK
Completed 422 Unprocessable Entity in 30ms

ActiveRecord::RecordInvalid - Validation failed: Category can't be blank:

1 个答案:

答案 0 :(得分:1)

您似乎有两个控制器,一个名为ProductsController,另一个名为Admin::ProductsController。如果您注意到错误日志,则会看到请求将转到ProductsController#create而不是Admin::ProductsController#create

您已在category_id 允许Admin::ProductsController,但ProductsController

更新form,如下所示:

<%= nested_form_for [:admin, @product] do |f| %>

因此,在提交表单时,它会指向正确的控制器,即Admin::ProductsController

<强>更新

  

但我只有一个&#34; show&#34; ProductsController中的操作

更新ProductsController的路线,如下所示:

resources :products, only: [:show] 

而不是

resources :products