Time.new does not work as I would expect - ruby-on-rails

I am trying to generate some seed material.
seed_array.each do |seed|
Task.create(date: Date.new(2012,06,seed[1]), start_t: Time.new(2012,6,2,seed[2],seed[3]), end_t: Time.new(2012,6,2,seed[2] + 2,seed[3]), title: "#{seed[0]}")
end
Ultimately I will put random hours, minutes, seconds. The problem that I am facing is that instead of creating a time with the 2012-06-02 date it creates a time with a different date: 2000-01-01.
I tested Time.new(2012,6,2,2,20,45) in rails console and it works as expected. When I am trying to seed my database however some voodoo magic happens and I don't get the date I want.
Any inputs are appreciated. Thank you!
Update1:
(0.0ms) begin transaction SQL
(0.5ms) INSERT INTO "tasks" ("created_at", "date", "description",
"end_t", "group_id", "start_t", "title", "updated_at") VALUES (?, ?,
?, ?, ?, ?, ?, ?) [["created_at", Tue, 03 Jul 2012 02:15:34 UTC
+00:00], ["date", Thu, 07 Jun 2012], ["description", nil],
["end_t", 2012-06-02 10:02:00 -0400], ["group_id", nil],
["start_t", 2012-06-02 08:02:00 -0400], ["title", "99"],
["updated_at", Tue, 03 Jul 2012 02:15:34 UTC +00:00]]
(2.3ms) commit transaction
This is a small sample of the log.
Update 2
Task id: 101, date: "2012-06-26", start_t: "2000-01-01 08:45:00", end_t: "2000-01-01 10:45:00", title: "1", description: nil, group_id: nil, created_at: "2012-07-03 02:15:33", updated_at: "2012-07-03 02:15:33"
This is what shows up in rails console.

Sounds like you used the :time type for your start_t and end_t. In that context time refers to a pure time of day data type, with no date, because that's what the SQL time type is.
Ruby's Time type covers both date and time, so your database column needs to be :datetime. In fact ruby has no pure time of day class so activerecord uses a regular Time with a bogus date instead.

I have tested you code like this:
arr = [1,2,3]
arr.each do |seed|
Timetest.create(time: Time.new(2012,6,2,2,20,45), title: "#{seed}")
end
And its working as expected. But i got this sql on my console and its a bit different than yours in your start_t and end_t
SQL (4.1ms) INSERT INTO "timetests" ("created_at", "time", "title", "updated_at") VALUES (?, ?, ?, ?) [["created_at", Tue, 03 Jul 2012 02:11:35 UTC +00:00], ["time", Sat, 02 Jun 2012 07:20:45 UTC +00:00], ["title", "1"], ["updated_at", Tue, 03 Jul 2012 02:11:35 UTC +00:00]]
Update 1
Have you tried to use DateTime.new instead of Time.new?
Task.create(date: DateTime.new(2012,06,seed[1]), start_t: DateTime.new(2012,6,2,seed[2],seed[3]), end_t: DateTime.new(2012,6,2,seed[2] + 2,seed[3]), title: "#{seed[0]}")

Related

has_many through middle model not creating, but creating duplicate of one model

I have two models join by a middle model
class Integration < ActiveRecord::Base
has_many :integration_records
has_many :records, through: :integration_records
end
class IntegrationRecord < ActiveRecord::Base
belongs_to :integration
belongs_to :record
end
class Record < ActiveRecord::Base
has_many :integration_records
has_many :integrations, through: :integration_records
end
i = Integration.create(whatever)
i.records.create(whatever)
=> (0.1ms) BEGIN
SQL (8.7ms) INSERT INTO "records" ("created_at", "updated_at") VALUES ($1, $2) RETURNING "id" [["created_at", Sat, 03 May 2014 00:31:02 UTC +00:00], ["updated_at", Sat, 03 May 2014 00:31:02 UTC +00:00]]
SQL (0.6ms) INSERT INTO "records" ("created_at", "updated_at") VALUES ($1, $2) RETURNING "id" [["created_at", Sat, 03 May 2014 00:31:06 UTC +00:00], ["updated_at", Sat, 03 May 2014 00:31:06 UTC +00:00]]
(0.4ms) COMMIT
i.records
=> [one record]
Record.all.count
=> 2
i.integration_records
=> #<IntegrationRecord id: nil, integration_id: 1, record_id: 2 >
Notice id is nil
IntegrationRecord.all
=> #<ActiveRecord::Relation []>
IntegrationRecord.create
=> #<IntegrationRecord id: nil, integration_id: nil, record_id: nil>
Notice id is nil
Record.create.integrations.create
=> (0.1ms) BEGIN
SQL (8.7ms) INSERT INTO "integrations" ("created_at", "updated_at") VALUES ($1, $2) RETURNING "id" [["created_at", Sat, 03 May 2014 00:31:02 UTC +00:00], ["updated_at", Sat, 03 May 2014 00:31:02 UTC +00:00]]
SQL (0.6ms) INSERT INTO "records" ("created_at", "updated_at") VALUES ($1, $2) RETURNING "id" [["created_at", Sat, 03 May 2014 00:31:06 UTC +00:00], ["updated_at", Sat, 03 May 2014 00:31:06 UTC +00:00]]
(0.4ms) COMMIT
Not sure why this is happening, in the case of i.records.create(whatever) it should output:
SQL (0.6ms) INSERT INTO "records" ("created_at", "updated_at") VALUES ($1, $2) RETURNING "id" [["created_at", Sat, 03 May 2014 00:31:06 UTC +00:00], ["updated_at", Sat, 03 May 2014 00:31:06 UTC +00:00]]
(0.4ms) COMMIT
INSERT INTO "integration_records" ("created_at", "data", "integration_id", "updated_at") VALUES ($1, $2, $3, $4) RETURNING "id" [["created_at", Sat, 03 May 2014 15:57:05 UTC +00:00], ["data", {}], ["integration_id", 5], ["updated_at", Sat, 03 May 2014 15:57:05 UTC +00:00]]
I should note that for some reason, when I create a new app in rails 4.0.4, I still had this problem. But when I change the names of the models and specifically Record model, it works perfectly fine. So when I changed it to Recordrow no problem at all.
As per your current association setup, all you need to do is, just follow these simple instructions step by step
Create an Integration record
## this will create an "integration" record in "integrations" table
integration = Integration.create(whatever)
Create an associated Record record
## this will create an associated "record" entry in "records" table
## PLUS this will also created an associated record in "integration_records" table
integration.records.create(whatever)
View the associated records and associated integration_records
## Display all the "records" entries associated to this particular integration
integration.records
## Display all the "integration_records" entries associated to this particular integration
integration.integration_records
UPDATE
i.records.create(whatever) was creating 2 records, found out that the issue was with the name records of the table. Once changed everything works fine. It looks like records is reserved word.
Also, OP found this link which states records is reserved

Rails Postgresql Time Column

I've got 2 Time Without Time Zone columns in my table (start_time and end_time). When an event occurs, I need to see which of these columns has a start_time < Time.now < end_time. The problem seems to be that Rails is not saving the Time in UTC and is instead saving the time exactly as I enter it in my field. My local timezone is UTC -5, so if I put in an end_time of 09:00:00, I would expect that to get saved to the database as 14:00:00, but it's getting saved as 09:00:00, so when I later run my start_time < Time.now < end_time query, I'm getting the wrong results (I'm off by those 5 hours).
Here's an example (the model is called TimeParameter):
1.9.3-p392 :001 > TimeParameter.create(start_time: "00:30:00", end_time: "09:00:00")
(7.0ms) SELECT * FROM geometry_columns WHERE f_table_name='time_parameters'
(0.2ms) BEGIN
SQL (9.8ms) INSERT INTO "time_parameters" ("created_at", "day_of_week", "end_time", "start_time", "updated_at") VALUES ($1, $2, $3, $4, $5) RETURNING "id" [["created_at", Tue, 23 Jul 2013 14:29:06 UTC +00:00], ["day_of_week", nil], ["end_time", 2000-01-01 09:00:00 UTC], ["start_time", 2000-01-01 00:30:00 UTC], ["updated_at", Tue, 23 Jul 2013 14:29:06 UTC +00:00]]
(308.9ms) COMMIT
=> #<TimeParameter id: 24, start_time: "2000-01-01 00:30:00", end_time: "2000-01-01 09:00:00", day_of_week: nil, created_at: "2013-07-23 14:29:06", updated_at: "2013-07-23 14:29:06">
Local time is ~09:30, UTC is ~14:30
Notice that the updated_at and created_at reflect the 14:30 UTC time but my start_time and end_time are not converted to UTC before being saved.
Ruby version: 1.9.3-p392
Rails version: 3.2.13

rails 3 create sets values to bill

So after a merge, my RoR 3 project no longer does 'creates' correctly. Default attributes get set correctly, but not the ones I pass in:
1.9.3-p125 :020 > f=Ifilter.create(:name => "test2", :regex => "()" )
SQL (101.5ms) INSERT INTO "ifilters" ("created_at", "name", "regex", "updated_at") VALUES (?, ?, ?, ?) [["created_at", Sat, 10 Mar 2012 03:36:24 UTC +00:00], ["name", nil], ["regex", nil], ["updated_at", Sat, 10 Mar 2012 03:36:24 UTC +00:00]]
=> #<Ifilter id: 2, name: nil, regex: nil, created_at: "2012-03-10 03:36:24", updated_at: "2012-03-10 03:36:24">
However, save still works:
1.9.3-p125 :021 > f=Ifilter.new
=> #<Ifilter id: nil, name: nil, regex: nil, created_at: nil, updated_at: nil>
1.9.3-p125 :022 > f.name = "test"
=> "test"
1.9.3-p125 :023 > f.regex = "()"
=> "()"
1.9.3-p125 :024 > f.save
SQL (4.8ms) INSERT INTO "ifilters" ("created_at", "name", "regex", "updated_at") VALUES (?, ?, ?, ?) [["created_at", Sat, 10 Mar 2012 04:13:10 UTC +00:00], ["name", "test"], ["regex", "()"], ["updated_at", Sat, 10 Mar 2012 04:13:10 UTC +00:00]]
=> true
What's going on?
Thanks!
Looks like you may have attr_accessible on your model. http://api.rubyonrails.org/classes/ActiveModel/MassAssignmentSecurity/ClassMethods.html#method-i-attr_accessible
If you are using it, attributes that aren't explicitly listed won't get set via #new, #create, and #update_attributes (and a few more).
This usually happens when you have attribute whitelisting enabled. Make sure you define the attributes that are settable via mass-assignment in your model via the attr_accessible macro:
class Ifilter
attr_accessible :name, :regex
...
end

In Rails, why would saving a new record return nil, and nothing gets saved?

I initialize an AdUnit object au with
au = AdUnit.new( cp )
where cp is equal to:
{:name=>"second56", :description=>nil, :target_window=>"BLANK", :explicitly_targeted=>false, :ad_unit_sizes_attributes=>[{:height=>90, :width=>728, :is_aspect_ratio=>false, :environment_type=>"BROWSER"}], :dfp_id=>"22319511", :parent_id_dfp=>"22261791"}
and the resulting object au is
#<AdUnit id: nil, dfp_id: "22319511", parent_id_dfp: "22261791", parent_id_bulk: nil, name: "second56", description: nil, target_window: "BLANK", explicitly_targeted: false, created_at: nil, updated_at: nil>
At this point, au.valid? and au.new_record? both return true.
If I do au.save (or au.save! for that matter) the result is nil and nothing is saved to the database. but if I do
aud = au.dup
aud.save
the result is true and the record is saved.
I can save my object with the duplicate workaround, but this looks really weird to me. can anybody give any ideas as to why is this happening? Below the SQL fragments from the 2 save statements from Rails console.
Thanks in advance all Rails gurus.
Returning nil and not saving:
SQL (1.0ms) INSERT INTO "ad_units" ("created_at", "description", "dfp_id", "explicitly_targeted", "name", "parent_id_bulk", "parent_id_dfp", "target_window", "updated_at") VALUES (?, ?, ?, ?, ?, ?, ?, ?, ?) [["created_at", Wed, 04 Jan 2012 17:28:37 UTC +00:00], ["description", nil], ["dfp_id", "22400631"], ["explicitly_targeted", false], ["name", "zapiFirstLevel366"], ["parent_id_bulk", nil], ["parent_id_dfp", "1166751"], ["target_window", "BLANK"], ["updated_at", Wed, 04 Jan 2012 17:28:37 UTC +00:00]]
=> nil
Returning true and saving:
SQL (0.9ms) INSERT INTO "ad_units" ("created_at", "description", "dfp_id", "explicitly_targeted", "name", "parent_id_bulk", "parent_id_dfp", "target_window", "updated_at") VALUES (?, ?, ?, ?, ?, ?, ?, ?, ?) [["created_at", Wed, 04 Jan 2012 17:29:58 UTC +00:00], ["description", nil], ["dfp_id", "22400631"], ["explicitly_targeted", false], ["name", "zapiFirstLevel366"], ["parent_id_bulk", nil], ["parent_id_dfp", "1166751"], ["target_window", "BLANK"], ["updated_at", Wed, 04 Jan 2012 17:29:58 UTC +00:00]]
=> true
OK, this was caused by the usage of accepts_nested_attributes_for when AdUnit has a has_and_belongs_to_many relationship with AdUnitSize. So I got to learn that these 2 do not work together nicely.
The only thing is, it might be good to have a warning somewhere, instead of having to find out about it from .save returning nil on a valid? = true object instead of true or false.
Using save! raises an exception if the record is invalid. It doesn't return anything.
If you need a return value use only save.
Basically if save! didn't raise, the record is saved successfuly. If you don't see it, then you're probably loading it wrong.

rails acts_as_list position auto increment

I am using the acts_as_list gem but when creating new Object the position should automatic increase in size and order position ASC.
LessonPage Model
class LessonPage < ActiveRecord::Base
acts_as_list :scope => 'lesson_id = #{lesson_id}'
default_scope order('position ASC')
end
Select
SELECT "lesson_pages".* FROM "lesson_pages" ORDER BY position ASC, "lesson_pages".id desc
Insert - first
INSERT INTO "lesson_pages" ("created_at", "lesson_id", "position", "updated_at") VALUES (?, ?, ?, ?) [["created_at", Sun, 16 Oct 2011 11:55:27 CEST +02:00], ["lesson_id", 2], ["position", 1], ["updated_at", Sun, 16 Oct 2011 11:55:27 CEST +02:00]]
Second
INSERT INTO "lesson_pages" ("created_at", "lesson_id", "position", "updated_at") VALUES (?, ?, ?, ?) [["created_at", Sun, 16 Oct 2011 11:57:15 CEST +02:00], ["lesson_id", 2], ["position", 2], ["updated_at", Sun, 16 Oct 2011 11:57:15 CEST +02:00]]
Third
INSERT INTO "lesson_pages" ("created_at", "lesson_id", "position", "updated_at") VALUES (?, ?, ?, ?) [["created_at", Sun, 16 Oct 2011 11:58:13 CEST +02:00], ["lesson_id", 2], ["position", 2], ["updated_at", Sun, 16 Oct 2011 11:58:13 CEST +02:00]]
Here it fails, because position should be 3 and not 2. How do I fix this?
thanks!!
I think it was fixed by this commit, but there is no release after this fix. I think you should use the code from github.
use this:
gem 'acts_as_list', :git => 'https://github.com/swanandp/acts_as_list.git'

Resources