2016-02-12 72 views
0

我想在模型中創建自定義驗證。 但什麼回報,當我試圖擺脫變量如何獲取ActiveRecord模型中的對象值?

該值這是我的模型

validate :permanent_event_check 

private 

    def permanent_event_check 
    param_activity = @activity 

    # puts "param_activityparam_activityparam_activity" 
    # puts @activity 
    # puts param_activity 
    # puts "param_activityparam_activityparam_activityparam_activity" 

    if param_activity.permanent == "false" 
     if param_activity.start_at == "" || param_activity.end_at == "" 
     @activity.errors[:base] << "You can't leave start and end date blank with Permanent Event" 
     return false 
     end 
    end 
    end 

這是我的控制器

def create 
    @activity = admin_current_user.activities.build(activity_param) 
    if @activity.save 
     flash[:success] = "Activity Created!" 
     redirect_to admin_dashboard_url 
    else 
     render 'new' 
    end 
    end 

private 

    def activity_param 
    params.require(:activity).permit(:name,:details,:start_at,:end_at, 
            :activity_image01_url,:activity_image02_url,:activity_image03_url, 
            :youtube_url,:capacity,:booking_status,:rules,:apply_details, 
            :payment_price,:payment_need,:avaliable,:rating,:temple_id) 
    end 

但它返回nil當我試圖讓來自我的模型中@activity的值。

我該如何解決這個問題? 謝謝!

回答

1

你不能像模型中那樣分配對象,而是你自己。

validates :permanent_event_check 
 

 
private 
 

 
    def permanent_event_check 
 
    if self.permanent == "false" 
 
     if self.start_at == "" || self.end_at == "" 
 
     self.errors[:base] << "You can't leave start and end date blank with Permanent Event" 
 
     return false 
 
     end 
 
    end 
 
    end

0

我認爲永久是布爾型,start_at和end_at - 日期時間。

validate :permanent_event_check, unless :permanent 

private 

def permanent_event_check 
     # if start_at and end_at are not filled they will be nil which is interpreted as false 
    unless start_at && end_at 
     self.errors[:base] << "You can't leave start and end date blank with Permanent Event" 
    end 
    end