我在包含的模型中遇到 Active Record 回调问题accepts_nested_attributes
我build_associated_parties
使用after_create
回调调用,但这些值没有被保存并且我得到<nil>
错误。我也尝试过使用before_create
&after_initialize
回调但没有成功。
是什么导致回调失败?
连接.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
连接控制器.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
如何使用模型中的代码完成相同的功能?将其保留在模型中是否有优势?