Rails 设计在创建新用户后创建相关对象?
Rails devise create a related object after new user is created?
使用Rails 4.1和Devise 3.0.3,如何在实例化User时在User上创建关联对象并将两者连接起来?
def User
has_one :case
end
def Case
belongs_to :user
end
在这种情况下,用户设置了设计。
我想做的是像这样实例化一个对象:
@case = Case.new
current_user.case = @case
或
current_user.case << @case
当向 "registrations#new" 发出请求时,如何执行此代码?
以下是我的实现方式:
class User < ActiveRecord::Base
...
before_action :create_case, only: [:new, :create]
def create_case
case = Case.create
self.case = case.id
# Maybe check if profile gets created and raise an error
# or provide some kind of error handling
end
end
您可以在用户模型中使用 create 方法。类似这样的东西:
def self.create(username, email, pass)
user = User.new(:username => username, :email => email, :password => pass)
user.case = Case.new
return user if user.save
end
我认为您必须覆盖 Devise::RegistrationsController#create
并且在创建操作中您必须采取 resource
并执行类似这样的操作 resource.build_case
http://guides.rubyonrails.org/association_basics.html#has_one-association-reference
覆盖 Devise::RegistrationsController 的 create
操作并将块传递给它:
# app/controllers/registrations_controller.rb
class RegistrationsController < Devise::RegistrationsController
def create
super do
resource.case = Case.new
resource.save
end
end
end
使用Rails 4.1和Devise 3.0.3,如何在实例化User时在User上创建关联对象并将两者连接起来?
def User
has_one :case
end
def Case
belongs_to :user
end
在这种情况下,用户设置了设计。
我想做的是像这样实例化一个对象:
@case = Case.new
current_user.case = @case
或
current_user.case << @case
当向 "registrations#new" 发出请求时,如何执行此代码?
以下是我的实现方式:
class User < ActiveRecord::Base
...
before_action :create_case, only: [:new, :create]
def create_case
case = Case.create
self.case = case.id
# Maybe check if profile gets created and raise an error
# or provide some kind of error handling
end
end
您可以在用户模型中使用 create 方法。类似这样的东西:
def self.create(username, email, pass)
user = User.new(:username => username, :email => email, :password => pass)
user.case = Case.new
return user if user.save
end
我认为您必须覆盖 Devise::RegistrationsController#create
并且在创建操作中您必须采取 resource
并执行类似这样的操作 resource.build_case
http://guides.rubyonrails.org/association_basics.html#has_one-association-reference
覆盖 Devise::RegistrationsController 的 create
操作并将块传递给它:
# app/controllers/registrations_controller.rb
class RegistrationsController < Devise::RegistrationsController
def create
super do
resource.case = Case.new
resource.save
end
end
end