我们可以像这样使用 ActiveRelation:
MyModel.where(:field => "test").create => #<Message ... field:"test">
但它不适用于具有多态 has_one 关联的连接:
class RelatedModel < AR::Base
# has :some_field
belongs_to :subject, :polymorphic => true
end
class MyModel < AR::Base
# need some dirty magic here
# to build default related_model with params from active_relation
has_one :related_model, :as => :subject, :dependent => :destroy
end
describe MyModel do
it "should auto-create has_one association with joins" do
test = MyModel.joins(:related_model).where("related_models.subject_type" => "MyModel", "related_models.some_field" => "chachacha").create
test.related_model.should_not be_nil
test.related_model.some_field.should == "chachacha"
test.related_model.subject_type.should == "MyModel"
test.related_model.subject_id.should == test.id
# fails =)
end
end
是否可以提取 active_relation 参数,将它们传递给 MyModel 以在 before_create 中使用并使用它们构建相关模型?