mardi 22 janvier 2019

How to push an object into ActiveRecord::Relation in rails 5

I am stuck in weird situtaion, I am working on upgrading an existing rails 3 appliction to rails 5 app.

Using rails 3, I have an object report which has many organizations

@report.organizations
#<ActiveRecord::Relation [#<Organization id: 1, name: "Org 1", description: nil, created_at: "2012-01-27", updated_at: "2019-01-15">]>
@report.organizations.count    # 1

when I push a new org object into existing activerecord relation it gives me new activerecord relation including new org

@report.organizations<< Organization.new
[#<Organization id: 1, name: "Org 1", description: nil, created_at: "2012-01-27", updated_at: "2019-01-15">, #<Organization id: nil, name: nil, description: nil, created_at: nil, updated_at: nil>]
# Getting count
@report.organizations.count    # 2

Using rails 5, I am getting exception

@report.organizations << Organization.new
*** NoMethodError Exception: undefined method `<<' for #<Organization::ActiveRecord_Relation:0x00007f93483e2640>

and when I do like

@report.organizations.to_a << Organization.new

it gives me

[#<Organization id: 1, name: "Org 1", description: nil, created_at: "2012-01-27", updated_at: "2019-01-15">, #<Organization id: nil, name: nil, description: nil, created_at: nil, updated_at: nil>]

but count is stil 1 instead of two

@report.organizations.count    # 1

Hope my issue is clear to you, please help me how to fix this issue. Thanks

Aucun commentaire:

Enregistrer un commentaire