具有类型数据的字段数组在条件验证时始终返回nil

时间:2017-03-20 08:16:54

标签: ruby-on-rails mongoid

我的模型广告系列包含字段:

class Campaign
   field :title, type: String
   field :start_date, type: Date
   field :end_date, type: Date
   field :locations, type: Array, default: []
   field :is_deleted, type: Boolean, default: false
   field :disabled, type: Boolean, default: false

   validate: :conflict_date, if: :check_location

   belongs_to :native_ad

   private

   def check_location
      locations.include?('Location 1') || locations.include?('Location 2')
   end

   def conflict_date
       ## another condition
   end
end

创造&更新记录操作正在运行,locations方法上存在check_location的值,但在更新单个属性时,如:

def destroy
    @campaign = Campaign.find(params[:id])
    @campaign.update_attributes(is_deleted: true)
    ## other stuff
end

locations始终返回nil

check_location方法调试器:

[1] pry(#<Campaign>)> locations
=> nil
[2] pry(#<Campaign>)> self
=> #<Campaign _id: 58ca3fa7fe37a86982000000, created_at: 2017-03-16 07:32:59 UTC, updated_at: 2017-03-16 07:32:59 UTC, start_date: 2017-03-16 00:00:00 UTC, end_date: 2018-03-16 00:00:00 UTC, locations: nil, disabled: false, is_deleted: true, native_ad_id: BSON::ObjectId('58ca3b52fe37a86590000000')>
[3] pry(#<Campaign>)> end_date
=> Fri, 16 Mar 2018
[4] pry(#<Campaign>)> start_date
=> Thu, 16 Mar 2017

注意:位置的值存在于数据库

创建行动

def create
   @campaign = Campaign.new(campaign_params)
   if @campaign.save
      redirect_to campaigns_path
   else
      render :new      
   end
end

private

def campaign_params
   params.require(:campaign).permit(:start_date, :end_date, :native_ad, locations: [])
end

我使用:

  • 导轨。 4.2.4
  • Mongoid 5.0.0

0 个答案:

没有答案