2017-03-01 93 views
1

从接触控制器具有内部编辑的动作...ActiveRecord的铲运营商<<

@programs << @contact.program 

将会产生以下错误:

NoMethodError - undefined method `<<' for Program::ActiveRecord_Relation 

联系型号:

belongs_to :program 

程序模式:

has_many :contacts 
validates :name, presence: true, uniqueness: true 

@programs.class 
Program::ActiveRecord_Relation 

@contact.program.class 
Program(id: integer, name: string, active: boolean, created_at: datetime, updated_at: datetime) 

问:为什么此操作失败?为什么不能将记录添加到记录集合中。什么是阻止收集(ActiveRecord_Relation)添加记录?

+0

我需要添加联系人的程序来编程,这全是 – user6337901

+0

'程序'不'has_many:程序'。如果你想简单地坚持“联系人的程序”,只需调用'.save'就可以了。 – coreyward

回答

1

你在这里自相矛盾:

Program has_many contacts VS Programs << Contact.program

如果你想添加一个Contact到某个特定的程序,你会在看添加联系人:

program.contacts << contact 

并且如果您尝试设置该联系人的程序:

contact.program = program 

然而,没有任何意义的是尝试添加一些东西到“程序”,这不是一种关系。因为您已定义has_many :programs,因此@programs.<<不可能对关系起作用。

+0

程序<< contact.program # user6337901

+0

程序<< contact.program – user6337901

+0

user6337901

0

您收到此错误,因为ActiveRecord::Relation类只是ActiveRecord查询返回的结果的集合。你可能通过运行Program.where或类似的查询来获得它。它不是ActiveRecord::Association,因此您无法为其添加更多记录。

您必须改为使用父对象返回的关联。

下面是你在做什么的例子,你VS应该做的事情:

class User < ApplicationRecord 
    has_many :programs 
end 

class Program < ApplicationRecord 
    belongs_to :user 
end 

new_program = Program.new 

# What you're attempting. 
programs_where = Program.where(user_id: User.first) # Class is Program::ActiveRecord_Relation 
programs_where << new_program # Throws Error b/c << is not available on ActiveRecord::Relation objects. 

# What you should be attempting. 
user = User.first 
programs_assoc = user.programs # Returns Programs::ActiveRecord_Associations_CollectionProxy 
programs_assoc << new_program # Returns Correctly 

注:@programs是如何定义目前尚不清楚。这个答案不适用于你,那么请提供完整的控制器代码,以及你正在使用的其他模型。