使用Rails 4.1和Devise 3.0.3,如何在实例化用户并连接两者时在User上创建关联对象?
def User
has_one :case
end
def Case
belongs_to :user
end
在这种情况下,用户设置了设计。
我想要做的是实例化一个像这样的对象:
@case = Case.new
current_user.case = @case
或
current_user.case << @case
当请求“注册#new”时,如何执行此代码?
答案 0 :(得分:1)
以下是我将如何实现这一点:
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
答案 1 :(得分:1)
覆盖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
答案 2 :(得分:0)
您可以在用户模型中使用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
答案 3 :(得分:0)
我认为您必须覆盖Devise::RegistrationsController#create
并在创建操作中必须执行resource
并执行类似resource.build_case
http://guides.rubyonrails.org/association_basics.html#has_one-association-reference