Create action inside another controller

559 views Asked by At

I am attempting to create a new User inside a controller for my Request class, but have having some difficulty. Below is my 'create' action inside my Requests controller. I realize I can't just call User.new, but am unsure how to structure the correct POST action.

def create
  @request = Request.new(params[:request])
  @user = User.find_by_email(@request.email)
  if @user.present?
    @request.user_id = @user.id
    @request.save
  else
    user = User.new
    user.email = @request.email
    user.zip = @request.zip
    user.save
    @request.user_id = user.id
    @request.save
  end

  respond_to do |format|
    if @request.save
      UserMailer.request_confirmation(@request).deliver
      UserMailer.request_notification(@request).deliver
      format.html { redirect_to confirmation_url }
      format.json { render json: @request, status: :created, location: @request }
    else
      format.html { render action: "new" }
      format.json { render json: @request.errors, status: :unprocessable_entity }
    end
  end
end
1

There are 1 answers

1
Piotr Imbierowicz On

I'm not sure what's your problem, but you don't have to call User create POST action (action from User controller) to create user.

User.create - 'create' is method from ActiveRecord::Base, not from UserController.

In one action (e.g. Request create action) you can create many ActiveRecord object, no matter what class they are.

There are various ways to create database entity in rails. They could be called from models, controllers and others.

@u = User.new
@u.save! # try to save object in DB, if something goes wrong, throws exception

@u = User.create! # creates empty user object in database, '!' causes that if something goes wrong, create throws exception

@u = User.create # it won't throw exception even if object is invalid

@u = User.new
@u.email = @request.email
if @u.save
   # ok, it's in DB
else
   # something goes wrong, e.g. rails validations
end