开发者

ruby on rails Model validations with arrays

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 fi开发者_开发百科eld 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


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
0

上一篇:

下一篇:

精彩评论

暂无评论...
验证码 换一张
取 消

最新问答

问答排行榜