Alexandr Savvinov
Alexandr Savvinov

Reputation: 21

Rails 5 how to create nested attributes

fuel_consumption.rb

class FuelConsumption < ApplicationRecord
  after_initialize :set_defaults, unless: :persisted?

  def set_defaults
    self.date ||= Date.today
  end

  belongs_to :boiler
  validates :fuel, numericality: {message: 'Поле может быть только числовое'}
  validates :fuel, presence: 'Поле топлива не может быть пустым'
  validates_uniqueness_of :date, scope: :boiler_id, message: 'Эта дата уже заполнена'
  validates :date, presence: 'Дата не может быть пустой'
end

new.html.slim

h4 Расход топлива
  = form_for(@branch, url: {action: 'create'}, method: 'post') do |f|
    = f.fields_for :boilers do |ff|
      = ff.fields_for :fuel_consumption do |fff|
        .form-group
          = fff.label :fuel, 'Дата'
          = fff.text_field :date, class: 'form-control', disabled: 'disabled', value: I18n.l(Date.today, format: :long)
        .form-group
          = fff.label :fuel, 'Количество топлива'
          = fff.text_field :fuel, class: 'form-control'
    .form-group
      = f.submit 'Сохранить', class: "btn btn-lg btn-success"

fuel_consumption_controller.rb

  def new
    @branch = current_user.branches.first
    # @fuel_consumption = FuelConsumption.new
  end
  def create
    @branch = current_user.branch.update_attributes(branch_params)

    if @branch
      render :success
    else
      flash.alert = 'Oops'
      render :action => 'new'
    end
  end


  def branch_params
    params.require(:branch).permit!
  end

I have assigned to user 1 branch, which have few (4 or 5) boilers, and i want to create fuel consumption on each boiler from one page, how to achieve that. This code updates attributes, but doesn't create fuel_consumption.

Upvotes: 1

Views: 3919

Answers (2)

KcUS_unico
KcUS_unico

Reputation: 513

in addition to the above answer you should double check if you permit the params in your controller. There are some very nice tutorials on setting up nested attributes.

For instance: http://railscasts.com/episodes/196-nested-model-form-part-1

Hope it helps.

Upvotes: 0

zwippie
zwippie

Reputation: 15515

My guess is that you forgot to allow the nested attributes to be set in your model(s), for example in models/branch:

accepts_nested_attributes_for :boilers

Upvotes: 3

Related Questions