rails acts_as_list position auto increment - ruby-on-rails

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'

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

Create action always creates two identical table entries instead of one

I have a create action in my ProductsController (the params come from a form in my view):
def create
vendor = #current_vendor
product = Product.create(:name => params[:product][:name])
vendor.products << product
vendor.belongings.create(:product_id => product.id, :count => params[:belonging][:count], :detail => params[:belonging][:detail])
if vendor.save
flash[:notice] = "Produkt hinzugefügt!"
redirect_back_or_default root_url
else
render :action => :new
end
end
It creates a variable "vendor", which stores the currently logged-in vendor (Authlogic)
A new Product is created (the product name is from the input field in the form) and stored in the variable "product"
The "product" is being connected to the current vendor
In the belongings table, additional informations to the product are being stored
it saves the whole thing
It's a many-to-many relationship throught the belongings table.
My problem is, the create action always creates the product twice!
Thanks for your help! :)
My console log when I create a new object through my form is:
Started POST "/products" for 127.0.0.1 at 2013-09-15 20:40:26 +0200
Processing by ProductsController#create as HTML
Parameters: {"utf8"=>"✓", "authenticity_token"=>"lNk/qQMP0xhlCuGgHtU+d5NEvIlCFcPSKB0FxDZH0zY=", "product"=>{"name"=>"Erdbeeren"}, "belonging"=>{"count"=>"20", "detail"=>"Rot"}, "commit"=>"Create"}
DEPRECATION WARNING: ActiveRecord::Base#with_scope and #with_exclusive_scope are deprecated. Please use ActiveRecord::Relation#scoping instead. (You can use #merge to merge multiple scopes together.). (called from current_vendor_session at /Users/reto_gian/Desktop/dici/app/controllers/application_controller.rb:11)
Vendor Load (0.3ms) SELECT "vendors".* FROM "vendors" WHERE "vendors"."persistence_token" = '04f75db0e2ef108ddb0ae1be1da167536d47b4d79c60ecb443ad2ea5717ecd752388e581f9379746568c72372be4f08585aa5581915b1be64dc412cded73a705' LIMIT 1
(0.1ms) begin transaction
SQL (0.8ms) INSERT INTO "products" ("created_at", "name", "updated_at") VALUES (?, ?, ?) [["created_at", Sun, 15 Sep 2013 18:40:26 UTC +00:00], ["name", "Erdbeeren"], ["updated_at", Sun, 15 Sep 2013 18:40:26 UTC +00:00]]
(0.8ms) commit transaction
(0.1ms) begin transaction
SQL (0.6ms) INSERT INTO "belongings" ("created_at", "product_id", "updated_at", "vendor_id") VALUES (?, ?, ?, ?) [["created_at", Sun, 15 Sep 2013 18:40:26 UTC +00:00], ["product_id", 7], ["updated_at", Sun, 15 Sep 2013 18:40:26 UTC +00:00], ["vendor_id", 1]]
(0.9ms) commit transaction
(0.1ms) begin transaction
SQL (0.6ms) INSERT INTO "belongings" ("count", "created_at", "detail", "product_id", "updated_at", "vendor_id") VALUES (?, ?, ?, ?, ?, ?) [["count", "20"], ["created_at", Sun, 15 Sep 2013 18:40:26 UTC +00:00], ["detail", "Rot"], ["product_id", 7], ["updated_at", Sun, 15 Sep 2013 18:40:26 UTC +00:00], ["vendor_id", 1]]
(0.9ms) commit transaction
Redirected to http://localhost:3000/
Completed 302 Found in 30ms (ActiveRecord: 5.1ms)
I think the problem could be in the line
vendor.products << product
this is adding the variable product (which is Product.create(:name => params[:product][:name]) to vendor.products a second time - which is unnecessary and likely the source of your problem

Why google maps for rails gem creating location with nil longtitude?

I have such problem. I'm using google_maps_for_rails gem and it is can't find location correctly. I run all instructions from documentation.
Here is my application.erb:
<%= yield :scripts%>
My model:
attr_accessible :address, :latitude, :longtitude
acts_as_gmappable
def gmaps4rails_address
self.address
end
but when I create location I get object with nil longtitude. Here is log:
INSERT INTO "locations" ("address", "created_at", "latitude", "longtitude", "name",
"updated_at") VALUES (?, ?, ?, ?, ?, ?) [["address", "Lviv"], ["created_at", Thu, 07
Feb 2013 10:56:45 UTC +00:00], ["latitude", 49.839683], ["longtitude", nil], ["name",
nil], ["updated_at", Thu, 07 Feb 2013 10:56:45 UTC +00:00]]
Can someone help me ?
See your code:
attr_accessible :address, :latitude, :longtitude
Typo: longtitude
Note that you can personalize the fields according to my doc:
acts_as_gmappable :lat => "latitude", :lng => "longtitude"

Time.new does not work as I would expect

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]}")

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.

Resources