Search code examples
ruby-on-railsmodel-view-controllerassociationsnested-attributes

Why association does not add a new record to my table?


I have 2 models: Chocolate and Kind, where chocolate class looks like:

class Chocolate < ActiveRecord::Base
  has_many :kinds, inverse_of: :chocolate
  accepts_nested_attributes_for :kinds

and Kind class looks like:

class Kind < ActiveRecord::Base
  belongs_to :chocolate

I have the next simple form, which contains:

= simple_form_for @chocolate do |ch|
  = ch.simple_fields_for :kinds, @chocolate.kinds.build(kind: 'Bitter') do |k|
    = k.input :kind
  = ch.input :netto 
  = ch.submit

So, when I submit my form, it adds a new record to my chocolates table, but it does not add a record to my kinds table, through associations.

In ChocolateController I have:

private
def chocolate_params
  params.require(:chocolate).permit(:netto, kinds_attributes: [:kind])
end

So, why it does not write to my table with associations? Where have I a mistake?


Solution

  • How to use nested models with simple form: https://github.com/plataformatec/simple_form/wiki/Nested-Models

    so, you need something like:

    = simple_form_for @chocolate do |ch|
      = ch.simple_fields_for :kinds ...