[英]Rails Active Record Callbacks error in nested association
我在包含accepts_nested_attributes
的模型中處理Active Record回調時遇到問題
我使用after_create
回調調用build_associated_parties
,但是這些值未保存,並且出現<nil>
錯誤。 我也嘗試過使用before_create
和after_initialize
回調沒有成功。
是什么導致回調失敗?
connection.rb
class Connection < ActiveRecord::Base
attr_accessible :reason, :established, :connector, :connectee1,
:connectee2, :connectee1_attributes,
:connectee2_attributes, :connector_attributes
belongs_to :connector, class_name: "User"
belongs_to :connectee1, class_name: "User"
belongs_to :connectee2, class_name: "User"
accepts_nested_attributes_for :connector, :connectee1, :connectee2
belongs_to :permission
after_create :build_associated_parties
# builds connectee's, connector, permission objects
def build_associated_parties
build_connector
build_connectee1
build_connectee2
build_permission
end
connection_controller.rb
class ConnectionsController < ApplicationController
def new
@connection = Connection.new
end
def create
@connection = Connection.new params[:connection]
if @connection.save
flash[:notice] = "Connection created successfully!"
redirect_to @connection
else
render :new
end
end
end
但是,如果我改為按如下所示在控制器內部構建這些屬性,則不會收到該錯誤。 很好,但這似乎與將業務邏輯代碼排除在控制器之外是違背的。
class ConnectionsController < ApplicationController
def new
@connection = Connection.new
@connection.build_connectee1
@connection.build_connectee2
@connection.build_connector
end
end
如何使用模型中的代碼完成相同的功能? 將其保留在模型中是否有優勢?
創建connection
后,您調用了方法build_associated_parties
,因此這些方法如何:
build_connector
build_connectee1
build_connectee2
build_permission
知道它將使用什么參數? 因此,他們不知道將什么值傳遞給方法,那么它們將得到錯誤。 在controller中,它們沒有錯誤,因為它們使用了params[:connection]
。
在表單上,如果您已經具有用於connector, connectee1, connectee2
字段,則應將用於初始化對象的代碼放入新控制器中。 保存@connection
,它也保存了那些對象。 我認為這些代碼無需納入模型。 您的模型僅應放置其他邏輯代碼,例如搜索或計算...
after_create
是一個很大的問題。 在模型中使用after_initialize
,並在build_associated_parties
方法中使用self
。 看看是否可行。
將邏輯移出控制器,再移回模型。 但是, build_*
代碼覆蓋了我傳遞給嵌套屬性的值。
通過將除非{attribute}添加到這些build_
方法中,我可以正確地傳遞值。
類Connection <ActiveRecord :: Base attr_accessible:原因,:已建立,:connector,:connectee1,,connectee2,:connectee1_attributes,:connectee2_attributes,:connector_attributes
belongs_to :connector, class_name: "User"
belongs_to :connectee1, class_name: "User"
belongs_to :connectee2, class_name: "User"
accepts_nested_attributes_for :connector, :connectee1, :connectee2
belongs_to :permission
after_initialize :build_associated_parties
validates :reason, :presence => true
validates_length_of :reason, :maximum => 160
#builds connectee's, connector, permission objects
def build_associated_parties
build_connector unless connector
build_connectee1 unless connectee1
build_connectee2 unless connectee2
end
聲明:本站的技術帖子網頁,遵循CC BY-SA 4.0協議,如果您需要轉載,請注明本站網址或者原文地址。任何問題請咨詢:yoyou2525@163.com.