I'm testing with RSpec and rspec-rails 2.10.
I've set Rails timezone as UTC at environment.rb, but RSpec time zone becomes my local timezone, Tokyo.
I've wrote Time.zone setteing at environments/test.rb and spec_helper.rb but didin't fixed.
How to set RSpec time zone?
The problem is another point.
I wrote a method which adjust time zone offset, and the method changes the Rails time zone.
Here is the code.
class WeeklyEvent < ActiveRecord::Base
def adjust_time_zone_offset
Time.zone = timezone # => This is the problem. Rails Time.zone changes to timezone.
time_zone_offset = Time.zone.utc_offset # => 32400 JST offset 9 hours in seconds.
self.start_date_time = (start_date_time - time_zone_offset).in_time_zone('UTC')
end
end
japanese_event = WeeklyEvent.find(1)
p japanese_event.start_date_time #=> Sun, 01 Jan 2012 09:00:00 JST +09:00
Use Time.zone.now instead of Time.now.
Related
I am using the gem amistad to manage friendships in my application.
I would like to track when relationships occur to be able to display some notifications.
First, I would like to add a timestamp to the relationship model in order to be able to do queries such as : retrieve all Friendships where receiving user is current user, and where updated_at is greater than the last time the current_user checked his notifications. By counting those results I can say: 3 incoming contact requests and display them.
So I made a migration:
class AddUpdatedAtToFriendship < ActiveRecord::Migration
def change
change_table :friendships do |t|
t.timestamps
end
end
end
rake db:migratemigrates correctly, but then the updated_at is not automatically when records are created or updated via the gem (eg: #user.invite another_user).
FYI, the invite method is the following: (code here)
def invite(user)
return false if user == self || find_any_friendship_with(user)
Amistad.friendship_class.new{ |f| f.friendable = self ; f.friend = user }.save
end
I don't see why the active record auto timestamps doesn't work in this case.
Note: If I manually create a friendship in the console, the timestamps are set:
$> rails c
test = Amistad::Friendships::UserFriendship.new
test.friend_id = 1
test.friendable_id = 2
test.save
test.updated_at
=> Thu, 23 May 2013 17:59:17 CEST +02:00
Even If I do that in the console timestamps are set : So it must be a context problem...
$> rails c
test2 = Amistad.friendship_class.new{ |f| f.friendable = User.find_by_id(5) ; f.friend = User.find_by_id(6) }.save
test2.updated_at
=> Thu, 23 May 2013 18:02:05 CEST +02:00
But still, when I call #user.invite another_user in the application, it doesn't update the timestamps...
Second, in the rails console, if I type Friendships.all, Friendship.all, Amistad::Friendships.all... I get :
NameError: uninitialized constant Friendship
How can I solve those 2 problems. Any suggestions ?
To access the Friendship model, use: Amistad::Friendships::UserFriendship.all
The migration is fine. There is nothing else to do in order to have the fields automatically updated.
Don't forget to restart the server so that Active Record picks up the changes of the migration !
I use rails 3.1, formtastic 2.0.2 and datepicker ui
I made datepicker_input.rb:
class DatepickerInput < Formtastic::Inputs::StringInput
include Formtastic::Inputs::Base
def input_html_options
super.merge(:class => "datepicker")
end
end
In application.js I wrote:
$('input.datepicker').datepicker()
I use it in my form like :as => :datepicker. I see calendar, pick date and everything is fine except for it doesn't fill column in my model. The only thing that I noticed is that when I fill first date and then all the other fields - it works. When date field is the last - it doesn't work. There is no errors, params[:model_name][:date_field] is not empty just nil in place of date that I chose.
Error was in date format - database just couldn't take format that returned datepicker.
I'm trying to make it so that I can have a urls like this:
/events
/events/sunday # => The day is optional
However, it doesn't seem to be working even though I know it is getting called. It is at the bottom of my routes file.
match '/:post(/:day_filter)' => 'posts#index', :as => post_day_filter, :constraints => DayFilter.new
class DayFilter
def initialize
#days = %w[all today tomorrow sunday monday tuesday wednesday thursday friday saturday]
end
def matches?(request)
return #days.include?(request.params[:day_filter]) if request.params[:day_filter]
true
end
end
Here is my rake routes output:
post_day_filter /:post(/:day_filter)(.:format) {:controller=>"posts", :action=>"index"}
I'm not sure what the problem is, specifically, but the following is a much more performance-friendly way of doing the same thing:
class ValidDayOfWeek
VALID_DAYS = %w[all today tomorrow sunday monday tuesday wednesday thursday friday saturday]
def self.matches?(request)
VALID_DAYS.include? request.params[:day_of_week]
end
end
get ':/post_type(/:day_of_week)' => 'posts#index', :constraints => ValidDayOfWeek
The biggest difference is that this avoids initializing a new ValidDayOfWeek object on every request. The Rails guide gives an example where you might want a fresh object each time (real-time blacklist updating), but it's misleading for cases like yours.
Also, you were getting a bit verbose in your matches? method — no need for explicit returns or a conditional, as includes? will return either true or false as is.
I have a date of birth in the rails model and I display it in different places. Every time I have to specifically format it in mm/dd/yyyy format. Is there something I can do in my model so that every time I get the dob out it comes in mm/dd/yyyy format.
You can define a quick formatted_birthday method in your model, but if you're just outputting this to views you can use Rails' built in date formatting output:
http://guides.rubyonrails.org/i18n.html#adding-date-time-formats
# config/locales/en.yml
en:
time:
formats:
birthday: "%m/%d/%Y"
Then in your view just use:
<%= l person.birthday, :format => 'birthday' %>
Or you can change birthday to default in the format definition and you can omit the :format option all together.
Yes you can. In config/initializers/some_initializer.rb
Date::DATE_FORMATS[:default] = "%m/%d/%Y"
Now all your dates will always be out in the above format.
If you want to selectively choose it only sometimes. Then
Date::DATE_FORMATS[:myformat] = "%m/%d/%Y"
And then you can use whereever you like
your_date.to_s(:myformat)
I asked a question regarding this yesterday, but it was muddled and didn't make sense, so I'm going to boil it down to the core issue.
I have an entries table. When a new record is saved, the entries_controller adds a time to the date column, which is recorded as a datetime. In the new method, I declare a new DateTime as so:
#entry.date = DateTime.new( params[:year].to_i, params[:month].to_i, params[:day].to_i )
I then include it as a hidden field with formtastic:
<%= f.input :date, :as => :hidden %>
Once the entry is saved to the database, the date field looks like 2011-02-10 00:00:00. Everything is working as planned so far, but when I try to retrieve that entry by querying against the date field, I get nil.
I've tried:
search_date = DateTime.new(2011,2,10)
Entry.find_by_date(search_date)
=> nil
I've even tried to search by string, which doesn't make sense since it's a datetime field.
search_time = '2010-02-10 00:00:00'
Entry.find_by_date(search_date)
=> nil
What am I doing wrong here? Why can't I retrieve the record by date?
Would this work for you?
Entry.where("date = #{search_date}")
I just tested this in Rails 3.0.4, mysql2 0.2.6 and
Entry.find_by_date(DateTime.new(2011,2,10))
works.
Having said that, why are you using a datetime column to save a date? Other than it just being a bad idea, you possibly could be running into some kind of timezone issues based on your rails and sql settings. Some automatic timezone conversion could explain the behaviour you are observing but that's just a guess. Please check the development server logs to see if rails is indeed generating the query you wish it to generate.