Varis Darasirikul
Varis Darasirikul

Reputation: 4187

How to get object value in ActiveRecord Model?

I want to create custom validation inside The Model. But nothing in return when i tried to get that value from the variable

This is my model

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

This is my controller

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

But it return nil when i tried to get the value from @activity inside my model.

How can i fix this? Thanks!

Upvotes: 0

Views: 41

Answers (2)

Plamena Gancheva
Plamena Gancheva

Reputation: 700

I assume that permanent is boolean, start_at and end_at - datetime.

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

Upvotes: 0

Sravan
Sravan

Reputation: 18657

You cannot assign the object like that in the model, instead you van take self.

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

Upvotes: 1

Related Questions