使用CRUD设计模型

时间:2016-03-05 14:51:10

标签: ruby-on-rails devise

问题:当我create.save来宾时,错误显示ActionController::UnknownFormat in GuestsController#create,通过记录保存。任何想法如何摆脱它?

我有:

  • rails g devise guest;
  • rails g controller guests用于CRUD界面。

guests_controller.rb:

class GuestsController < ApplicationController
  before_action :set_guest, only: [:show, :edit, :update, :destroy]
  def new
    @guest = Guest.new
  end
  def edit
    @guest = Guest.find(params[:id])
  end
  def create
    respond_to do |format|
      @guest = Guest.new(guest_params)
      if @guest.save
        redirect_to guests_path, notice: 'Client was successfully created.'
      else
        render :new
      end
    end
  end

  def update
    #update without changing password
    if params[:guest][:password].blank?
      params[:guest].delete(:password)
      params[:guest].delete(:password_confirmation)
    end
    #usual actions
    @guest = Guest.find(params[:id])
    if @guest.update_attributes(guest_params)
      sign_in(@guest, :bypass => true) if @guest == current_guest
      redirect_to guests_path, notice: 'Client was successfully updated.'
    else
      render :edit
    end
  end

  private
    def set_guest
      @guest = Guest.find(params[:id])
    end
    def guest_params
      params.require(:guest).permit(:email, :password, :password_confirmation)
    end
end

可能在注册/控制器中有一些重定向?...

我尝试了路线devise_for :guests, controllers: { registrations: 'guest_registrations' } + guest_registrations_controller.rb

class GuestRegistrationsController < Devise::RegistrationsController
  protected

  def after_sign_up_path_for(guest)
    guests_path # Or :prefix_to_your_route
  end
end

但它没有做任何事情

1 个答案:

答案 0 :(得分:1)

您正在使用respond_to,但您没有说出响应格式

请改为尝试:

def create
    respond_to do |format|
      format.html do
        @guest = Guest.new(guest_params)
        if @guest.save
          redirect_to guests_path, notice: 'Client was successfully created.'
        else
          render :new
        end
      end
    end
end

响应格式可以是:json, :html, :xml, :js

比上述版本更好的版本:

def create
    respond_to do |format|
         @guest = Guest.new(guest_params)
         if @guest.save
           format.html { redirect_to guests_path, notice: 'Client was successfully created' }
           format.json {render json: @guest}
         else
            format.html { render :new }
            format.json { render json: @guest.errors.full_messages, status: :bad_request }
         end
     end
end