Rails 3 can't get beginning_of_week - ruby-on-rails-3

Have a publish_on datetime field.
Just trying to get to the begining_of_week from the publish_on.
Tried a helper
def start_week(publish_on)
DateTime.parse(publish_on).beginning_of_week
end
and in view <%= start_week(#survey.publish_on) %>
Tried in my model
def set_start_week
publish_on.beginning_of_week
end
Hell, even tried this helper
def this_should_work
DateTime.now.beginning_of_week
end
But everything returns a invalid date to my view. It works in irb, why not in my view?
EDIT
module SurveysHelper
require 'date'
require 'time'
def this_should_work
DateTime.now.beginning_of_week
end
end
take_survey.html.erb
<%= this_should_work %>
Error
invalid date

I encountered the same problem when trying to use ActiveSupport outside of Rails. I found the answer here:
http://guides.rubyonrails.org/active_support_core_extensions.html
Here is the key bit:
require 'active_support/all'
Have you customized your rails stack to no longer include ActiveSupport?

In rails 3.0.9 I got
undefined method `at_beginning_of_week'
wherever I put it, my alternative solution is:
def SomeMethodPutAnywhere
...
#datey = Date.today
#monday = #datey - #datey.wday + 1
##monday is now the monday of the current week.
#Remove the constant '+1' if your week begins sunday...
...
end

Related

How can I use a datepicker in ActiveAdmin without rewriting the create form?

My ActiveAdmin model creation forms (ie. /admin/<model>/new) are using an awkward set of dropdowns for dates and datetimes.
I'd like to use pickers instead. But all the documentation I've found about using a datetime picker appears to require rewriting the whole form. There doesn't seem to be a way to change just one input, nor an equivalent of preserve_default_filters!.
I'd like to either change the default for all date and datetime columns, something like...
config.datepicker = ...
Or per column, like...
column :signed_up, as: :datetime_picker
EDIT
By default I get new and edit forms equivalent to this.
form do |f|
f.semantic_errors
f.inputs
f.actions
end
If I want to change signed_up to use a datepicker, I have to repeat all the columns supplied by default just to change the input type of one column.
ActiveAdmin.register Thing do
form do |f|
t.semantic_errors
t.input :name
t.input :this
t.input :that
t.input :signed_up, as: :datepicker
t.input :other
t.input :thing
t.input :left
t.input :right
t.actions
end
end
That's a lot of unnecessary repetition, and the formatting doesn't come out right. I'm looking for a way to change the input presentation of one column, or one type, without having to manually write the whole form every time.
Try the DateNTimePickerActiveAdmin Rubygem. It works really well and is customisable according to your project.
You can find the documentation here: https://github.com/NikhithaGraceJosh/date_n_time_picker_activeadmin
From the docs:
Gemfile
gem 'date_n_time_picker_activeadmin'
Code Sample (In your form)
f.input :column_name, as: :datetimepicker
CSS
In active_admin.scss, add the line,
#import date_n_time_picker_activeadmin
JS
In active_admin.js, add the line,
//= require date_n_time_picker_activeadmin
Hope it's useful!
I managed to monkey patch Active Admin behavior, to use :datepicker instead of :date_select.
In your config/application.rb, add following patches
Bundler.require(*Rails.groups)
// Start patch
module ActiveAdminFormBuilderPatch
def default_input_type(*_args, **_kwargs)
ret = super
ret == :date_select ? :datepicker : ret
end
end
ActiveAdmin::FormBuilder.include ActiveAdminFormBuilderPatch
// end patch
module YourApp
class Application < Rails::Application
// configs
end
end
Note
Confirmed this to be working on activeadmin version 2.9.0.
I used activeadmin_addons which does a lot of useful things, including using DateTimePicker for input, but not filters.
To get filters I use active_admin_datetimepicker which makes jQuery DateTimePicker available for inputs (:date_time_picker) and filters (:date_time_range). Then I monkey patched ActiveAdmin to use it by default.
# config/initializers/active_admin.rb
# Make the default filter type for a DateTime to be the DateTimeRange picker.
class ActiveAdmin::Filters::FormBuilder
protected
alias_method :original_default_input_type, :default_input_type
def default_input_type(method, options = {})
case column_for(method)&.type
when :datetime
return :date_time_range
end
original_default_input_type(method, options)
end
end

Ruby on Rails: Creating a Calendar, get the next week (redirect loop)

I'm creating a Calendar to view of a week without the Calendar gem. (It will get pretty specific past the use of that gem).
When I render a view to see a page (index) it will display the dates and days for that particular week. How can I make a button that is clickable that will change those dates to the previous week or the next week?
I'm confused on how to do it, and am looking for coding suggestions of course. How I have attempted this so far is I have created two helper functions to add the days to my current variables. Then I want to display the same page after the helper function updates to the next week or previous week.
Here is how I am calling my helper function
<%= link_to '<', week_ahead, class: 'month-arrow' %>
def week_ahead
#viewDate = #viewDate + 7.days
#weekStart = #viewDate.beginning_of_week(start_day = :monday)
end
helper_method :week_ahead
def week_back
#viewDate = #viewDate - 7.days
#weekStart = #viewDate.beginning_of_week(start_day = :monday)
end
helper_method :week_back
Here is what I am using in my controller
def index
#user = User.find(session[:user_id])
#viewDate = Date.today
#weekStart = #viewDate.beginning_of_week(start_day = :monday)
end
If I put a redirect_to user_path command in the helper function it gives a redirect loop. I still want my view to update to the next week when they click on the "next arrow".
Use simple calender gem. It is really helperful.https://github.com/excid3/simple_calendar

Rails field "can't be blank", even though it's not blank

I'm using Rails 3 and failing to submit a form because one of the fields fails to pass validates_presence_of. My model is called dinner, and the field, which is used in conjunction with a datepicker, is called date.
views/dinners/new.html.erb:
<%= f.text_field :date, id: "datepicker" %>
models/dinner.rb:
attr_accessible :date
validates_presence_of :date
dinners_controller.rb:
def create
#dinner = Dinner.new params[:dinner]
if #dinner.save
flash[:notice] = "Dinner created successfully."
redirect_to controller: 'dinners'
else
flash.now[:alert] = #dinner.errors.full_messages.join("<br>").html_safe
render action: "new"
end
end
Whenever I fill out all of the fields, including date, I get the error "Date can't be blank", even though it is not blank. What's going on here?
I've found the answer.
My date column was of type date, and before validation Rails ran .to_date on it. Unfortunately, the datepicker that I use creates dates in the American mm/dd/yy format, which Rails can't handle, so .to_date returned nil. That's why the date failed validation: because it really was nil, even though the POST request was fine.
I chose the easy solution and changed the default date of datepicker, as shown here.
Note: For my version of datepicker, I had to use format instead of dateFormat, and also had to use yyyy-mm-dd instead of yy-mm-dd because Rails String#to_date thinks that the year "13" is literally '0013' and not '2013'.

Calculating Elapsed time in Rails

I'm writing an app where I need to compare two :datetime fields and get the difference to display as an "elapsed" time from the start of the record. I think I have my code right, but I keep getting the below error. Can someone tell me what I'm doing wrong?
Error on view:
undefined method `-' for nil:NilClass line 26:
26: <td><%= link_to call.elapsed_time, call %></td>
Call.rb (abbreviated)
before_create :set_dispatched_time
def set_dispatched_time
self.dispatched_time = Time.now
end
def elapsed_time
self.dispatched_time - Time.now
end
My fields in PG are set as :datetime so that I can compute times (I did have them as strings.. ooops) but for some reason it's not calculating. Do I need to call Time.parse first or something like that? I'm not really sure which direction to go. I just want to subtract the dispatched_time field from Time.now
Your self.dispatched_time does not exist according the error message, it is nil. This can be because before_create is call when first time the opject is persisted into the database, and this particular instance is not yet saved.
First try to make sure, that this variable has a value, or assign a default value in case if it is not assigned. E.g.:
def elapsed_time
Time.now - (self.dispatched_time || Time.now)
end

Activeadmin - undefined method `batch_action'?

I'm trying to use activeadmin's batch_action so I can run actions on more than one record. However when trying to run my rails server I get the following error.
undefined method `batch_action' for #<ActiveAdmin::ResourceDSL:0xb11f980> (NoMethodError)
Here is the activeadmin resource code:
ActiveAdmin.register Product do
batch_action :destroy, false
filter :name
index do
selectable_column
column :name
default_actions
end
controller do
def current_company
#current_company
end
end
end
I'm not sure where I'm getting it wrong - I need to show a corresponding checkboxes against the records and then define a batch action. Where am I getting it wrong here?
Got the answer :) was a wrong entry in my gemfile.
https://github.com/gregbell/active_admin/issues/1302