Warning: file_get_contents(/data/phpspider/zhask/data//catemap/2/ruby-on-rails/57.json): failed to open stream: No such file or directory in /data/phpspider/zhask/libs/function.php on line 167

Warning: Invalid argument supplied for foreach() in /data/phpspider/zhask/libs/tag.function.php on line 1116

Notice: Undefined index: in /data/phpspider/zhask/libs/function.php on line 180

Warning: array_chunk() expects parameter 1 to be array, null given in /data/phpspider/zhask/libs/function.php on line 181
Ruby on rails 验证ActiveRecord模型是否具有相同的关联/组_Ruby On Rails_Ruby_Activerecord_Rails Activerecord - Fatal编程技术网

Ruby on rails 验证ActiveRecord模型是否具有相同的关联/组

Ruby on rails 验证ActiveRecord模型是否具有相同的关联/组,ruby-on-rails,ruby,activerecord,rails-activerecord,Ruby On Rails,Ruby,Activerecord,Rails Activerecord,因此,我试图在两个ActiveRecord模型上进行自定义验证。我正在处理的应用程序包含3个模型;一张便条,一位作家和一本笔记本。每当我通过表单创建便笺时,我都希望验证它是否具有与当前允许编写者在创建或更新时使用的笔记本完全相同的笔记本 模型看起来非常简单,就像这样 class Notebook < ApplicationRecord has_many :notes has_many :writers end class Writer < ApplicationReco

因此,我试图在两个ActiveRecord模型上进行自定义验证。我正在处理的应用程序包含3个模型;一张便条,一位作家和一本笔记本。每当我通过表单创建便笺时,我都希望验证它是否具有与当前允许编写者在创建或更新时使用的笔记本完全相同的笔记本

模型看起来非常简单,就像这样

class Notebook < ApplicationRecord
   has_many :notes
   has_many :writers
end

class Writer < ApplicationRecord
   has_many :notes
   belongs_to: notebook
end

class Note < ApplicationRecord
   belongs_to: writer
   belongs_to: notebook
end
another_notebook = Notebook.new

writer = Writer.new

note = Note.new(writer: writer, notebook: another_notebook)
note.save!

由于写入程序和笔记本之间没有关联,因此会引发验证错误。

首先创建间接关联:

class Notebook < ApplicationRecord
   has_many :notes
   has_many :writers, through: :notes
end

class Note < ApplicationRecord
   belongs_to: writer
   belongs_to: notebook
end

class Writer < ApplicationRecord
   has_many :notes
   has_many :notebooks, through: :notes
   # ...
end

不过,我会考虑这是否是一个很好的模型验证,因为它看起来更像是一个授权问题,应该由CcChanCAN或PunDIT来处理,而不是一个坏用户输入的问题,这是验证应该处理的问题。< /P>你能添加错误信息吗?谢谢马克斯的回答!正是我要找的!我可以理解你是如何说这更像是一个授权问题,但我想限制人们不能通过更改URL(/:notebook\u id/notes/:note\u id/edit)中的参数来为不同的笔记本创建不同的笔记。如果你正确设置控制器,他们无论如何都不能这样做。

class Writer < ApplicationRecord
   has_many :notes
   has_many :notebooks, through: :notes
   belongs_to :current_notebook, class: 'Notebook'
end

class Note < ApplicationRecord
  # ...
  validate :is_current_notebook

  def is_current_notebook
    unless notebook == writer.current_notebook
      errors.add(:notebook, 'is not valid.')
    end
  end
end