加入收藏 | 设为首页 | 会员中心 | 我要投稿 李大同 (https://www.lidatong.com.cn/)- 科技、建站、经验、云计算、5G、大数据,站长网!
当前位置: 首页 > 百科 > 正文

ruby-on-rails – 对has_many关联的Rails验证

发布时间:2020-12-17 02:58:22 所属栏目:百科 来源:网络整理
导读:我在孩子存在的has_many关系上遇到验证时遇到问题,但父母却没有.但是,在创建/保存父对象时,我想确保已保存特定的子级(具有某些属性). 有一个父对象has_many子对象. Child对象首先保留在数据库中,因此没有对父对象的任何引用.关联结构是: Parent - has_many
我在孩子存在的has_many关系上遇到验证时遇到问题,但父母却没有.但是,在创建/保存父对象时,我想确保已保存特定的子级(具有某些属性).

有一个父对象has_many子对象. Child对象首先保留在数据库中,因此没有对父对象的任何引用.关联结构是:

Parent
  - has_many :children 

Child
  - someProperty: string
  - belongs_to: parent

例如,有三个子对象:

#1 {someProperty: "bookmark",parent: nil}
#2 {someProperty: "history",parent: nil }
#2 {someProperty: "window",parent: nil }

仅当父项包含具有someProperty历史记录和窗口的子对象时,父项才有效.

我在控制器中设置父节点:

p = Parent.new(params[:data])
for type in %w[bookmark_id history_id window_id]
    if !params[type].blank?
        p.children << Child.find(params[type])
    end
end
// save the parent object p now
p.save!

当子项被分配给父项<<时,它们不会立即保存,因为父项的id不存在.为了保存父母,它必须至少有这2个孩子.我怎么能解决这个问题?欢迎任何输入.

解决方法

不知道为什么你需要做这样的事情,但无论如何,这样做怎么样?

class Parent <?ActiveRecord::Base

  CHILDREN_TYPES = %w[bookmark_id history_id window_id]
  CHILDREN_TYPES.each{ |c| attr_accessor c }

  has_many :children

  before_validation :assign_children
  validate :ensure_has_proper_children

private

  def assign_children
    CHILDREN_TYPES.each do |t|
      children << Child.find(send(t)) unless send(t).blank?
    end
  end

  def ensure_has_proper_children
    # Test if the potential children meet the criteria and add errors to :base if they don't
  end
end

控制器:

...
p = Parent.new(params[:data])
p.save!
...

如您所见,我首先将所有逻辑移至模型.然后,有一个两步拯救儿童的过程.首先,我们将子项分配给父项,然后验证它们是否符合所需条件(在那里插入逻辑).

抱歉做空.如有必要,我会回答任何进一步的问题.

(编辑:李大同)

【声明】本站内容均来自网络,其相关言论仅代表作者个人观点,不代表本站立场。若无意侵犯到您的权利,请及时与联系站长删除相关内容!

    推荐文章
      热点阅读