开发者

How to assign values using fields_for with a has_many association in rails 3

开发者 https://www.devze.com 2023-02-11 00:24 出处:网络
I have 2 models as described below. I would like to make it so that when a user creates a product, they have to select from the categories that exist in the categories table.

I have 2 models as described below. I would like to make it so that when a user creates a product, they have to select from the categories that exist in the categories table.

Tables:

products: id, name

categories: 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

views/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: Couldn't find Category with ID=3 for Product with ID=

I would like to just be able to assign an existing category to product on creation. Is there an easy way to do this?


You only need to use accepts_nested_attributes_for if you're actually updating categories from your form. If all you're doing is choosing a single category to add your new product to, you can simplify everything like this:

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

If you're only assigning a product to one category, you don't need a many-to-many relationship between them.

As for the view:

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

精彩评论

暂无评论...
验证码 换一张
取 消