创建关系模型但未保存时,Rails验证存在

时间:2015-06-12 18:22:27

标签: ruby-on-rails

我有两个模型任务 DependecyTask ,他们之间的关系很清楚代码。

当我尝试保存任务时, DependencyTask任务属性的验证任务存在:true 会给出您可以看到的错误,因为任务模型尚未保存。

如何在不删除验证的情况下解决此问题:任务?

型号:

class DependencyTask < ActiveRecord::Base
  belongs_to :task
  belongs_to :before, :class_name => "Task"

  validates :before, presence: true
  validates :task, presence: true
  validates :before_id, uniqueness: {scope: :task_id,
    message: "No puede ser la misma tarea dependiente de si misma"}

end

class Task < ActiveRecord::Base
  has_many :assignment_tasks, dependent: :destroy
  has_many :users, through: :assignment_tasks

  has_many :dependency_tasks, dependent: :destroy
  has_many :befores, :through => :dependency_tasks
  has_many :inverse_dependency_tasks, :class_name => "DependencyTask", :foreign_key => "before_id", dependent: :destroy
  has_many :inverse_befores, :through => :inverse_dependency_tasks, :source => :task

  accepts_nested_attributes_for :dependency_tasks

end

控制器:

class TasksController < ApplicationController

def create
    @task = @project.tasks.create(params[:task].permit(:name, :length, :start_date, :end_date, :milestone_id, :description, {before_ids: []}, {user_ids: []}, :form => [] ))
    respond_to do |format|
      if @task.save        
        format.html { redirect_to project_path(@project) }
        format.json { redirect_to 'edit', status: :created, location: @task }
      else
        format.html { render action: 'index' }
        format.json { render json: @task.errors, status: :unprocessable_entity }
      end
    end 
  end
end

发送到服务器的数据:

Processing by TasksController#create as HTML
  Parameters: {"utf8"=>"✓", "authenticity_token"=>"fYRkppGw8ekRS3aBMwKSw8IU+8ayBdUKDw20/QT0r/g=", "task"=>{"name"=>"Architecture building and Cost estimate", "length"=>"20", "start_date"=>"16/01/2015", "end_date"=>"30/01/2015", "description"=>"", "milestone_id"=>"", "before_ids"=>["", "6"]}, "commit"=>"Crear Tarea", "locale"=>"es", "project_id"=>"8"}

错误:

["Dependency tasks task Can't be blank"]
{
    :"dependency_tasks.task" => [
        [0] "Can't be blank"
    ]
}

所有有用的评论都会非常有用。

1 个答案:

答案 0 :(得分:0)

我使用inverse_of方法解决了这个问题

型号:

class DependencyTask < ActiveRecord::Base
  belongs_to :task, inverse_of: :dependency_tasks
  belongs_to :before, :class_name => "Task", inverse_of: :dependency_tasks

end



class Task < ActiveRecord::Base   

  has_many :dependency_tasks, dependent: :destroy, inverse_of: :task
  has_many :befores, :through => :dependency_tasks, inverse_of: :dependency_tasks
  has_many :inverse_dependency_tasks, :class_name => "DependencyTask", :foreign_key => "before_id", dependent: :destroy, inverse_of: :task
  has_many :inverse_befores, :through => :inverse_dependency_tasks, :source => :task, inverse_of: :inverse_dependency_tasks
end