views:

22

answers:

1

Hello 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  A: 

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
jigfox
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
winter sun
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.
jigfox