Warning: file_get_contents(/data/phpspider/zhask/data//catemap/2/ruby-on-rails/67.json): failed to open stream: No such file or directory in /data/phpspider/zhask/libs/function.php on line 167

Warning: Invalid argument supplied for foreach() in /data/phpspider/zhask/libs/tag.function.php on line 1116

Notice: Undefined index: in /data/phpspider/zhask/libs/function.php on line 180

Warning: array_chunk() expects parameter 1 to be array, null given in /data/phpspider/zhask/libs/function.php on line 181

Warning: file_get_contents(/data/phpspider/zhask/data//catemap/2/visual-studio-2010/4.json): failed to open stream: No such file or directory in /data/phpspider/zhask/libs/function.php on line 167

Warning: Invalid argument supplied for foreach() in /data/phpspider/zhask/libs/tag.function.php on line 1116

Notice: Undefined index: in /data/phpspider/zhask/libs/function.php on line 180

Warning: array_chunk() expects parameter 1 to be array, null given in /data/phpspider/zhask/libs/function.php on line 181
Ruby on rails Create有一个多态关联_Ruby On Rails_Activerecord_Ruby On Rails 4_Activemodel - Fatal编程技术网

Ruby on rails Create有一个多态关联

Ruby on rails Create有一个多态关联,ruby-on-rails,activerecord,ruby-on-rails-4,activemodel,Ruby On Rails,Activerecord,Ruby On Rails 4,Activemodel,在我的Rails 4应用程序中,我的开发人员模型只有一个用户,例如: class Developer < ActiveRecord::Base has_one :user, as: :account ... end classdeveloper

在我的Rails 4应用程序中,我的开发人员模型只有一个用户,例如:

class Developer < ActiveRecord::Base
  has_one :user, as: :account
  ...
end
classdeveloper
在我的用户模型中,我有

class User < ActiveRecord::Base
  belongs_to :account, polymorphic: true
end
class用户

当开发人员记录被创建时,我希望自动创建一个与开发人员关联的用户。这可能吗?或者有没有一种方法可以按照rails的指导原则来实现这一点?

这取决于您如何创建开发人员以及用户的属性来自何处。如果开发人员属性来自表单,我建议在开发人员模型上使用accepts\u nested\u attributes\u for。以下是有关如何使用嵌套属性的一些信息

是的,您可以在控制器中或通过回调(例如在创建之后)执行此操作。你试过了吗?我会在开发人员模型中这样做,使用类似于
self.create\u user
的事后回调。但是,当您可以使用一对多关联时,为什么首先需要使用多态关联,这一点并不明显。