验证ActiveRecord模型具有相同的关联/组

时间:2018-11-15 19:50:04

标签: ruby-on-rails ruby activerecord rails-activerecord

因此,我试图围绕两个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!

由于编写者和笔记本之间没有关联,因此引发验证错误。

1 个答案:

答案 0 :(得分:1)

首先,首先要创建间接关联:

{'data': [{'channel_id': 'UCqTFe5Dz3mpixUrLfMmY6dw', 'title': 'Manoyek', 'channel_img': 'https://yt3.ggpht.com/a-/AN66SAx-JBOt1_NI6nXTBL2R95kDBaR6Spy9i4_q-g=s240-mo-c-c0xffffffff-rj-k-no', 'desc': 'Jestem Adrian' , 'subscriberCount_gained': 587372, 'subscriberCount_lost': 0}]}

这将在Notebook和Writer之间建立多对多关联。

如果您随后要添加规则,则from pandas import DataFrame data = DataFrame.from_dict(diction) print(data) data_to_write = data[["channel_id", "channel_img", "desc"]]只能在特定笔记本中创建笔记:

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

但是我会考虑这是否真的适合模型验证,因为这似乎更多是由CanCanCan或Pundit处理的授权问题,而不是验证应处理的用户输入错误的问题。