我有两个模型,第一个模型是条目,这与我的控制器条目一起使用来创建一个新请求。我需要从条目中验证range_days小于或等于我的第二个模型empaccrl的范围。但不管我做的仍然得到一个未定义的方法范围...
我的参赛模式
class Entry < ActiveRecord::Base
self.primary_key = 'id'
validates :indirect_id, presence: true, allow_blank: false
validates :leave_range, presence: true, allow_blank: false
validates :range_days, presence: true, allow_blank: false, length: { maximum: 2 }
# Really wish I could get this validation to work ..............
validates :range_days, :numericality => { :less_than_or_equal_to => :range }, :presence => true
belongs_to :empaccrl
attr_accessible :emp_id, :person_id, :emp_dept, :emp_no, :emp_first_name, :emp_last_name, :emp_mail_addr, :indirect_id, :mgr_no, :mgr_first_name, :mgr_last_name, :mgr_mail_addr, :leave_range, :employee_type, :seq_no, :range_days, :alt_mgr_name, :alt_mgr_addr, :alt_mgr_no
# This is for the validation
def range
empaccrl.range
end
end
我的Empaccrl模型
class Empaccrl < ActiveRecord::Base
establish_connection :vdev
self.table_name = 'empaccrl'
belongs_to :entry
attr_accessor :range
end
带有create method和new
的我的Entry Controller def new
@entry = Entry.new
respond_to do |format|
format.html# new.html.haml
format.xml { render :xml => @entry }
end
end
def create
params.permit!
@entry = Entry.new(params[:entry])
respond_to do |format|
if @entry.save
EntryMailer.submit_for_approval(@entry).deliver
format.html { redirect_to(entry_path( @entry ), :notice => 'Entry successfully created.') }
format.xml { render :xml => @entry, :status => :created, :location => @entry }
else
format.html { render :action => "new" }
format.xml { render :xml => @entry.errors, :status => :unprocessable_entity }
end
end
端
这是我的参赛表
ID NUMBER(38,0)
CREATED_AT DATE
UPDATED_AT DATE
EMP_ID VARCHAR2(255 BYTE)
EMP_NO VARCHAR2(255 BYTE)
EMP_FIRST_NAME VARCHAR2(255 BYTE)
EMP_LAST_NAME VARCHAR2(255 BYTE)
EMP_MAIL_ADDR VARCHAR2(255 BYTE)
INDIRECT_ID VARCHAR2(255 BYTE)
MGR_NO VARCHAR2(255 BYTE)
MGR_FIRST_NAME VARCHAR2(255 BYTE)
RANGE_DAYS NUMBER(38,0)
这是我的Empaccrl表
PERSON_ID NUMBER(10,0)
IS_ACTIVE VARCHAR2(1 BYTE)
ACCRUAL_DATE DATE
RANGE NUMBER(10,0)
PROJECTED_ACCRUED NUMBER(12,5)
任何帮助都非常感谢我的眼睛因为长时间盯着它而燃烧!!!!!
答案 0 :(得分:1)
使用内置验证无法做到这一点。你需要写一个自定义的:
validates :range_days, :presence => true
validate :range_days_smaller_than_range, if: :range
private
def range_days_smaller_than_range
errors.add(:range_days, "LOL Nah! <Any error message or translation key here>") if range_days > range
end
答案 1 :(得分:0)
我让它上班!!!! 这就是我如何做到我希望它做的事感谢@BroiSatse的帮助!
validate :range_days_smaller_than_range, if: :range
def range
range = Empaccrl.where("person_id = ? and is_active = ?", '14052', 'Y').pluck(:range).first
end
private
def range_days_smaller_than_range
errors.add(:range_days, "Sorry you don't have days for this request") if range_days > range
end
端