Rails设计在创建新用户后创建相关对象?

时间:2015-04-07 06:00:29

标签: ruby-on-rails ruby devise

使用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”时,如何执行此代码?

4 个答案:

答案 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::RegistrationsControllercreate次操作并向其传递一个块:

# 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

的操作

https://github.com/plataformatec/devise/blob/master/app/controllers/devise/registrations_controller.rb

http://guides.rubyonrails.org/association_basics.html#has_one-association-reference