在子模型中访问父对象

时间:2015-02-02 06:17:35

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

我正在使用rails 2.3.17并建立此关系

class Item < ActiveRecord::Base
  belongs_to :order
end

class Order < ActiveRecord::Base 
  has_many :items, :dependent => :delete_all
end

现在我需要对项目进行验证,通过访问order对象属性,我该怎么做?

写作时

validate :checkXYZ

def checkXYZ
  Rails.logger.debug self.order // I AM GETTING NIL
end

但是当我写

before_save :checkXYZ

def checkXYZ
  Rails.logger.debug self.order // I AM ORDER OBJECT
end

这是我的控制器逻辑

@order = @otherObj.orders.create(params[:order])
item = @order.items.create(params[:item])

我需要在物品类的验证中获取订单对象,我该怎么做?

2 个答案:

答案 0 :(得分:1)

在before_validate部分中,父(订单)尚未连接到项目对象。因此,它绝对显示为零。

但在验证通过后&amp;在before_save阶段,顺序&amp;项目已连接,因此您可以访问所选项目的父订单。

您可以通过以下方法验证您的对象。

class Order < ActiveRecord::Base 
  has_many :items, dependent: :delete_all
end

class Item < ActiveRecord::Base
  before_save :something_missing?
  belongs_to :order

  private 
  def something_missing?  
     your_order = self.order 
      if (add_your_condition_which_is_violated)
        errors[:base] << "Your error message" 
        return false 
      end
       # When you are returning false here, the record won't be saved.
      # And the respective error message you can use to show in the view.
  end
end

答案 1 :(得分:0)

要在创建或更新订单时可靠地执行此操作,您应该在父对象(订单)模型上调用验证,如下所示:

class Order < ActiveRecord::Base 
    has_many :items, :dependent => :delete_all
    validate :checkXYZ

    private
    def checkXYZ
        Rails.logger.debug self // Here you will have the Order object
        for i in items do
            if (vehicle == 7 and i.distance <= 500) then // vehicle is an attribute of order
                errors.add(:error, "You're driving by car, distance must be larger than 500")
            end
        end
    end
end