2017-03-01 70 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是如何定義目前尚不清楚。這個答案不適用於你,那麼請提供完整的控制器代碼,以及你正在使用的其他模型。