如何在ActiveRecord模型中获取对象值?

时间:2016-02-12 07:25:36

标签: ruby-on-rails 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

但是当我试图从模型中的@activity获取值时,它返回nil。

我该如何解决这个问题? 谢谢!

2 个答案:

答案 0 :(得分:1)

你不能在模型中分配这样的对象,而是你自己。

&#13;
&#13;
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
&#13;
&#13;
&#13;

答案 1 :(得分:0)

我假设permanent是boolean,start_at和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