Ruby on rails 3 当用户注册时,如何向用户添加用户配置文件?(设计、轨道3)
我想覆盖Desive的Ruby on rails 3 当用户注册时,如何向用户添加用户配置文件?(设计、轨道3),ruby-on-rails-3,devise,Ruby On Rails 3,Devise,我想覆盖Desive的RegistrationsController“创建操作,以便当用户注册时,我可以将UserProfile模型与该用户关联 因此,按照Deave自述文件中的指导原则,我否决了该行动: #File app/controllers/registrations_controller.rb: class Users::RegistrationsController < Devise::RegistrationsController def create #
RegistrationsController
“创建操作,以便当用户注册时,我可以将UserProfile
模型与该用户关联
因此,按照Deave自述文件中的指导原则,我否决了该行动:
#File app/controllers/registrations_controller.rb:
class Users::RegistrationsController < Devise::RegistrationsController
def create
# some code here..
self.user_profiles.build #Error (no method `user_profiles`)
current_user.user_profiles.build #Error (current_user is nil)
some other way???
end
end
#File routes.rb:
devise_for :users, :controllers => { :registrations => 'users/registrations' }
self
在此上下文中指的是控制器,而不是模型
此外,用户模型是否有许多用户配置文件?否则,如果他们没有(即他们只有一个),那么您应该使用@user.build\u user\u profile
,而不是@user.user\u profiles.build
我还建议在模型级而不是控制器级执行此操作,使用回调,例如在创建前或创建后,即:
class User < AR
has_one :user_profile
after_create :build_profile
def build_profile
self.build_user_profile
...
end
end
class用户
谢谢!这很有效(@user.build\u user\u profile)。此外,我需要在控制器(而不是模型)中创建配置文件,因为在注册时需要用户的一些输入(例如地址)。如果您从另一个模型传入数据,在本例中是UserProfile,您可以查看使用:在用户模型中为
接受_嵌套的_属性_,在注册表单中为
接受
字段_,这样您就可以在模型级别执行所需的所有操作,事实上,它允许您隐式创建关联模型,而无需编写一行代码。再次感谢!我会调查的
class User < AR
has_one :user_profile
after_create :build_profile
def build_profile
self.build_user_profile
...
end
end