Jamesla
Jamesla

Reputation: 1408

How to do optional nested forms with form_for in rails 5

I have the following form with nested attributes. Which is working correctly.

However I want to make the points optional, meaning if you leave the summary field blank the form should still submit and create a debate without creating a point.

I have other forms that create points which rely on validates_presense_of :summary so I would rather keep that attribute there.

Is there some sort of rails form_for built in functionality that allows the nested form to be optional? (IE only if they fill out the fields)

debate.rb

class Debate < ApplicationRecord
  validates_presence_of :title
  accepts_nested_attributes_for :points
  has_many :points
end

point.rb

class Point < ApplicationRecord
  validates_presence_of :summary
  belongs_to :debate
end

_form.html.erb

<%= form_with(model: debate, local: true, class: "col-6") do |form| %>
  <%= form.text_field :title %>
  <%= form.fields_for :points do |point_form| %>
    <%= point_form.text_area :summary %>
  <% end %>
  <%= form.submit class: "btn btn-primary" %>
<% end %>

Upvotes: 2

Views: 704

Answers (1)

Thanh
Thanh

Reputation: 8604

You can try adding reject_if option:

accepts_nested_attributes_for :points, reject_if: proc { |attributes| attributes['summary'].blank? }

so it won't build new point record.

Upvotes: 2

Related Questions