How to assign values ​​using name_fields with has_many association in rails 3

I have 2 models as described below. I would like to make sure that when a user creates a product, they should choose from the categories that exist in the category table.

Tables:

Products: id, name

category: id, name

categories_products: category_id, product_id

class Product
    has_and_belongs_to_many :categories
    accepts_nested_attributes_for :categories
end

class Category
    has_and_belongs_to_many :products
end

class ProductsController < ApplicationController
    def new
        @product = Product.new
        @product.categories.build
    end

    def create
        @product = Product.new(params[:product])
        if @product.save
            redirect_to @product, :notice => "Successfully created product."
        else
            render :action => 'new'
        end
    end
end

view / products / new.haml

= form_for @product do |f|
    = f.text_field :name
    = f.fields_for :categories do |cat_form|
        = cat_form.collection_select :id, Category.all, :id, :name, :prompt => true

However, this fails and gives me: Could not find a category with ID = 3 for the product with identifier =

I would just like to assign an existing category to a product at creation. Is there an easy way to do this?

+3
source share
1 answer

accepts_nested_attributes_for, categories . , , , , :

class Product
  belongs_to :category
end

class Category
  has_many :products
end

class ProductsController < ApplicationController
  def new
    @product = Product.new
  end

  def create
    @product = Product.new(params[:product])
    if @product.save
      redirect_to @product, :notice => "Successfully created product."
    else
      render :action => 'new'
    end
  end
end

, " ".

:

= form_for @product do |f|
  = f.text_field :name
  = f.collection_select :category_id, Category.all, :id, :name, :prompt => true
+1

Source: https://habr.com/ru/post/1792940/


All Articles