如何在Rails 5中将对象推入ActiveRecord :: Relation

时间:2019-01-22 10:51:28

标签: ruby-on-rails ruby ruby-on-rails-3 ruby-on-rails-4 ruby-on-rails-5

我陷入了奇怪的情景,我正在努力将现有的Rails 3应用升级到Rails 5应用。

使用rails 3,我有一个对象报告,其中包含许多组织

@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

当我将新的org对象放入现有的activerecord关系中时,它为我提供了包括新的org在内的新的activerecord关系。

@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

使用rails 5,我遇到异常了

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

当我喜欢的时候

@report.organizations.to_a << 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>]

但计数是Stil 1而不是2

@report.organizations.count    # 1

希望我的问题对您很清楚,请帮助我解决此问题。谢谢

4 个答案:

答案 0 :(得分:0)

根据the guide,它应该可以工作。如果不是,请尝试使用create

 @report.organizations.create

答案 1 :(得分:0)

当您使用新的定义时,您需要保存该变量 例如

organization=Organization.new
organization.name = "organization 1"
organization.description= "Something description"
organization.save #save the array obj
Organization.count #1

其他使用create方法创建记录突然两者都相同

Organization.create(name:"org2",description: "something")
Organization.count #2

答案 2 :(得分:0)

这对我有用:

a=[]
a << @report.organizations
a.count # => 1
a << Organization.new
a.count # => 2

答案 3 :(得分:0)

这个怎么样:

@report_data = @report.organizations
@report_data.count # => 1
@report_data += [Organization.new]
@report_data.count # => 2