1

I have an array of tasks which the user needs to fill,
Its looks like this:

 <% form_for(@task) do |f| %>
 <%= error_messages_for 'task' %>
  <ul>
     <li><label>Task Name</label> <input type=text name="task_list[]"> </li>
     <li><label>Task Name</label> <input type=text name="task_list[]"> </li>
     <li><label>Task Name</label> <input type=text name="task_list[]"> </li>
  </ul>                                 
 <% end %>

Now I need to perform a validation that at list one field is not empty. When it was only one field I used to perform the validation in the model like this:

validates_presence_of :name,:message Task Name cannot be blank

But now when I use an array I don’t know how I can perform it
I will be happy for some guidance in this issue

Thanks

1 Answer 1

1

Try this:

class TasksController < ApplicationController
  def create
    unless params[:task_list].empty
      @task_list = returning Array.new do |task_list|
        params[:task_list].each do |task_name|
          task = Task.new
          task_list << task if task.valid?
        end
      end
      if @task_list.empty?
        # do whatever should be done if no valid task was found
      else
        # do whatever should be done if at least on task was valid
        # i.e. saving each task:
        @task_list.each(&:save)
      end
    end
  end
end
Sign up to request clarification or add additional context in comments.

2 Comments

This is working, but I was looking to do the validation from the model and not in the controller with the use of something like validates_presence_of methode
Sorry, but I don't understand what you want. You call here the valid method of the model. And this is almost always called from within the controller.

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.