0

I have 3 text_fields in my view in which I enter students name. Of course you can enter one student or three students but I want to make sure that at least one student was provided because a project must have a student assigned to it.

Here is my view:

<%= form_for @project, url: projects_path do |f| %>
    <p>
        <%= f.label :name, "Name" %>
        <%= f.text_field :name %>
    </p>

    <p>
        <%= f.fields_for :students do |s| %>
            <%= s.label :name %>
            <%= s.text_field :name %>
        <% end %>
    </p>

    <p>
        <%= f.submit "Submit" %>
    </p>
<% end %>

And new method from Projects controller:

  def new
    @project = Project.new()
    3.times do 
      student = @project.students.build
    end
  end

What I want to achieve is to check if at least one student was provided and if not just show alert or disable submiting.

Edit

Models used in this project:

class Student < ActiveRecord::Base
  belongs_to :project
end

class Project < ActiveRecord::Base
  has_many :students
  accepts_nested_attributes_for :students
  validate :validate_student_count

  def validate_student_count
    errors.add(:students, "at least one is required") if students.count < 1
  end
end
cojoj
  • 6,405
  • 4
  • 30
  • 52

2 Answers2

2

Lots of very similar questions on the internet. Here's some examples: Validate the number of has_many items in Ruby on Rails and Validate that an object has one or more associated objects

Community
  • 1
  • 1
Catfish
  • 18,876
  • 54
  • 209
  • 353
1

Just add a custom validation rule as:

  validate :validate_student_count

  def validate_student_count
    errors.add(:students, "at least one is required") if students.count < 1
  end
Yuriy Goldshtrakh
  • 2,014
  • 1
  • 11
  • 7