I have an active record called 'test'. Each test has a StartTime and an EndTime, which are in the datetime format in a MySQL database. I have a view that includes a search form with 2 datetime_local_fields:
<%= form_for :test, :url => { :action => :search }, :method => 'get' do %>
<div class="input-append">
<%= datetime_local_field :StartDate, params[:search] %><br />
<%= datetime_local_field :EndDate, params[:search] %><br />
<button class="btn" type="submit">Search</button>
</div>
<% end %>
This is the associated method from tests_controller.rb:
def search
if :StartDate
if :EndDate
@tests = Test.searchRange(:StartDate, :EndDate).order("StartTime DESC")
end
end
end
And from test.rb:
def self.searchRange (date1,date2)
where(['StartTime >= ? and EndTime <= ?', date1, date2])
end
I am returning 0 results each time! I can't figure out what is going wrong. I have an entry in my database where the starttime and endtime are both on 2015-10-22, and I search with the parameters 2015-06-01 and 2015-12-10. Why are the matching records not being returned?
:StartDate
in your controller is not what you expect: It is just the symbol :StartDate
. You will need something like: params[:StartDate]
to access the params send from the form:
def search
@tests = Test.scope
@tests = @tests.from_date(params[:StartDate]) if params[:StartDate]
@tests = @tests.to_date(params[:EndDate]) if params[:EndDate]
@tests = @tests.order("StartTime DESC")
end
And I would use scopes
in the model instead of class methods:
scope :from_date, ->(date) { where('StartTime >= ?', date) }
scope :to_date, ->(date) { where('EndTime <= ?', date) }
The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.