vendredi 31 juillet 2015

ActiveRecord::AssociationTypeMismatch in ProductosController#create

Im trying to create a new product (producto in spanish) which belongs to a category (categoria). When i submit the error shows:

ActiveRecord::AssociationTypeMismatch in ProductosController#create
Categoria(#47681880) expected, got String(#4043652)

Extracted source (around line #10):
def create
 @producto = Producto.new(params_producto)

 if @producto.save
redirect_to categorias_path, :notice => "se ha creado un producto"

My product controller:

class ProductosController < ApplicationController
 def new
  @producto = Producto.new
  @categoria = Categoria.all
 end
 def index
    @producto = Producto.all
 end
 def create
     @producto = Producto.new(params_producto)

     if @producto.save
         redirect_to categorias_path, :notice => "se ha creado un producto"
     else
      render 'new'
     end
 end
  def params_producto
   params.require(:producto).permit!
  end
def show
 @producto = Producto.find(params[:id])
end
end

products model

class Producto < ActiveRecord::Base
  belongs_to :categoria
  validates :nombre, uniqueness: { message: "ya existe"}

end

new html:

<%= form_for :producto, url: productos_path do |f| %>
  <% if @producto.errors.any? %>
   <div id="error_explanation">
     <ul>
    <% @producto.errors.full_messages.each do |msg| %>
      <li>El <%= msg %></li>
    <% end %>
  </ul>
  </div>
 <% end %>
 <p>
   <%= f.label :nombre %><br>
    <%= f.text_field :nombre %>
 </p>

 <p>
    <%= f.label :categoria %><br>
     <%= f.select :categoria_id, Categoria.all.collect {|x| [x.nombre, x.id]}, { :include_blank => "Select one" } %>
 </p>

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

Category model:

class Categoria < ActiveRecord::Base
  has_many :productos

end

im using rails 4.1

Aucun commentaire:

Enregistrer un commentaire