【问题标题】:Access parent attribute in child model rails访问子模型导轨中的父属性
【发布时间】:2016-08-15 07:00:07
【问题描述】:

正在为我的模型创建条件验证。要检查这一点,我需要检查 Parent.parent_attribute == "true"

validates :departure_date, presence: true, future: true, :if => :awesome_method?
 belongs_to :parent


 def awesome_method?
   if @parent.parent_attribute == "true"
     true
   else
     false
   end
 end

目前@parent.parent_attribute 正在返回 nil,即使有效负载有它。我想我遇到了一个问题,它无法访问 parent_attribute 因为它还没有保存......如何在设置验证之前检查父级是否有值?

更新 为了清楚起见,我同时创建了父母和孩子。 当我尝试使用Parent.find... 时,我回来了

找不到“parent_id”=CORRECT_INVOICE_NAME 的父项

更新 2 父母和孩子都有一个创建,但下面的 JSON 是创建父母和孩子的原因。

{
 “parent": {
   “parent_id": "PLZDONTSAVE",
   “data": 2525.25,
   “parent_attribute": true,

   “child_attributes":[
     { “child_toy": “123",
       “child_data": “ABC" }
   ]
 }
}

父控制器

  def create
    @parent = Parent.new(parent_params)
    if @parent.save
      render json: @parent, status: :created, location: @parent
    else
      render json: @parent.errors, status: :unprocessable_entity
    end
  end

  def parent_params
    params.require(:parent).permit(:parent_id, :parent_attribute,
    child_attributes:[:child_toy, :child_data, ])
  end

【问题讨论】:

    标签: ruby-on-rails ruby model


    【解决方案1】:

    除非您在某处定义@parent,否则它将是nil,就像@foo@bar。您只需使用不带“@”的parent,即可访问通过关联链接的对象(例如您的belongs_to)。

    所以试试这个:

      def awesome_method?
        parent.parent_attribute == "true"
      end
    

    【讨论】:

    • parent.parent_attribute 正在返回 > NoMethodError(nil:NilClass 的未定义方法 `parent_attribute')
    • 嗯,你能展示一下你同时创建父母和孩子的代码吗?
    • 更新了我的问题以证明我通过同时构建对象的意思
    • 啊,我明白了。看来你也想通了! :-)
    【解决方案2】:

    我通过使用以下内容更新两个模型来使其工作。在here的帮助下

    在子模型中

    belongs_to :parent, inverse_of: :child 
    

    在父模型中

    accepts_nested_attributes_for :children
    has_many :children, inverse_of: :parent
    

    再加上@tbreier 的建议,我们完成了工作。

    【讨论】:

      猜你喜欢
      • 1970-01-01
      • 1970-01-01
      • 2017-12-09
      • 1970-01-01
      • 1970-01-01
      • 2021-11-30
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      相关资源
      最近更新 更多