Rails不会重定向到Show动作

时间:2015-10-01 17:53:17

标签: ruby-on-rails

我有三种型号城市,区域和用户 单击提交按钮后,新用户表单服务器/应用程序未重定向到显示操作

(我的路线文件配置/路线)

Rails.application.routes.draw do
  resources :areas
  resources :cities
  get 'users/update_cities'
  resources :users

(用户控制器app / controllers / users_controller.rb)

class UsersController < ApplicationController
  before_action :set_user, only: [:show, :edit, :update, :destroy]

  def update_cities
    @areas = Area.where("city_id = ?", params[:city_id])

      respond_to do |format|
        format.js
      end

  end

  # GET /users
  # GET /users.json
  def index
    @users = User.all
  end

  # GET /users/1
  # GET /users/1.json
  def show
  end

  # GET /users/new
  def new
    @user = User.new
    @cities = City.all
    @areas = Area.where("city_id = ?", City.first.id)
  end

  # GET /users/1/edit
  def edit
  end

  # POST /users
  # POST /users.json
  def create
    @user = User.new(user_params)

    respond_to do |format|
      if @user.save
        @user.area_ids = [params[:user][:area_id]]
        format.html { redirect_to @user, notice: 'User was successfully created.' }
        format.json { render :show, status: :created, location: @user }
      else
        format.html { render :new }
        format.json { render json: @user.errors, status: :unprocessable_entity }
      end
    end
  end

  # PATCH/PUT /users/1
  # PATCH/PUT /users/1.json
  def update
    respond_to do |format|
      if @user.update(user_params)
        format.html { redirect_to @user, notice: 'User was successfully updated.' }
        format.json { render :show, status: :ok, location: @user }
      else
        format.html { render :edit }
        format.json { render json: @user.errors, status: :unprocessable_entity }
      end
    end
  end

  # DELETE /users/1
  # DELETE /users/1.json
  def destroy
    @user.destroy
    respond_to do |format|
      format.html { redirect_to users_url, notice: 'User was successfully destroyed.' }
      format.json { head :no_content }
    end
  end

  private
    # Use callbacks to share common setup or constraints between actions.
    def set_user
      @user = User.find(params[:id])
    end



    # Never trust parameters from the scary internet, only allow the white list through.
    def user_params
      params.require(:user).permit(:name, :brief,:area_id)
    end
end

和表单(app / views / users / _form.html.erb) (不包括标签只是为了清理d代码)

<%= form_for(@user, remote: true) do |f| %>
<%= f.text_field :name %>
<%= f.select :city_id, options_for_select(@cities.collect { |city|
    [city.name.titleize, city.id] }), {include_blank: 'Select Something'}, { id: 'cities_select'} %>


  <%= f.select :area_id, options_for_select(@areas.collect { |area|
    [area.name.titleize, area.id] }, 0), {}, { id: 'areas_select' } %>
<%= f.submit %>

请帮忙..!

1 个答案:

答案 0 :(得分:0)

表单中的remote:true参数导致问题。当您想要更新/创建对象而不更新您所在的视图时,此设置非常有用。

有关详细信息,请查看ruby on rails API