gpt4 book ai didi

ruby-on-rails - Ruby on Rails 中的动态选择菜单

转载 作者:行者123 更新时间:2023-12-02 01:33:16 24 4
gpt4 key购买 nike

提前感谢尝试或回答我的问题的人。我有 City 模型、Area 模型、User 模型。City 模型和 Area 模型具有“has_many”关联其中区域模型和用户模型具有“有很多通过”关联

我希望根据所选城市显示区域选择菜单,同时创建新用户选择城市选择菜单中的任何项目(提出AJAX请求)时,区域选择菜单应显示属于该城市的区域。

这是我的代码,请告诉我哪里错了。 (谢谢)

(app/views/users/_form)
<%= form_for(@user, remote: true) do |f| %>
<div class="field">
<%= f.label :name %><br>
<%= f.text_field :name %>
</div>
<p>
<%=f.collection_select :city_id, City.order(:name), :id, :name, include_blank: true%>
</p>

<div class="a"></div>

<div class="actions">
<%= f.submit %>
</div>
<% end %>

(app/controllers/users_controller.rb)

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

def custom
@tilu = 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
@areas= Area.all
end

# GET /users/1/edit
def edit
end

# POST /users
# POST /users.json
before_action :get_area, only:[:create]
def create
@user = User.new(user_params)

@user.area_ids = @area

respond_to do |format|
if @user.save
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
def get_area
@area = params[:user][:area_id]
end

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

(app/assets/javascripts/users.js.coffe)

jQuery ->
$(document).on 'change', '#user_city_id', (evt) ->
$.ajax '/users/custom',
type: 'GET'
dataType: 'html'
data: {
city_id: $('#user_city_id :selected').val()
}
error: (jqXHR, textStatus, errorThrown) ->
console.log("AJAX Error: #{textStatus}")
success: (data, textStatus, jqXHR) ->
console.log("Dynamic country select OK!")

(config/routes.rb)

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

(app/views/users/_customTemplate.html.erb)

<%=f.collection_select :area_id, Area.where(city_id: @tilu), :id, :name, include_blank: true %>

最后但并非最不重要的...(app/views/users/custom.js.erb)

$('.a').append("<%=j render 'customTemplate' %>");

求助!!

ruby 服务器控制台错误

Started GET "/users/custom?city_id=1" for 127.0.0.1 at 2015-09-30 21:20:01 +0530 Processing by UsersController#show as HTML
Parameters: {"city_id"=>"1", "id"=>"custom"} User Load (0.3ms) SELECT "users".* FROM "users" WHERE "users"."id" = ? LIMIT 1 [["id", 0]] Completed 404 Not Found in 76ms (ActiveRecord: 0.3ms)

ActiveRecord::RecordNotFound (Couldn't find User with 'id'=custom):
app/controllers/users_controller.rb:77:in `set_user'

Rendered /usr/local/lib/ruby/gems/2.2.0/gems/actionpack-4.2.1/lib/action_dispatch/middleware/templates/rescues/_source.erb (4.1ms)

浏览器控制台错误

GET http://localhost:3000/users/custom?city_id=1 404 (Not Found)send @ jquery-4075e3b7b3964707c653f61b66f46dec.js?body=1:9665jQuery.extend.ajax @ jquery-4075e3b7b3964707c653f61b66f46dec.js?body=1:9216(anonymous function) @ users-c743c610a872f962fb75a7ac244905cd.js?body=1:4jQuery.event.dispatch @ jquery-4075e3b7b3964707c653f61b66f46dec.js?body=1:4671elemData.handle @ jquery-4075e3b7b3964707c653f61b66f46dec.js?body=1:4339ListPicker._handleMouseUp @ about:blank:544 users-c743c610a872f962fb75a7ac244905cd.js?body=1:11 AJAX Error: error

最佳答案

好吧,问题太多了,我无法从中挑选出来;这就是我要做的:


您正在寻找名为 dynamic select menus 的东西.你在标题中提到了这一点,我只是想澄清一下术语。

当您更改选择框中的值时,动态选择菜单应该发送 ajax 请求。这个过程应该很简洁(即你只发送一个 ID 到你的 Controller ),你最终会得到一组返回的数据来填充下一个选择框:

#config/routes.rb
resources :cities do
get "update", to: "users#custom" #-> url.com/cities/:city_id/update
end
resources :users #-> put this below so that the users/show method doesn't catch the above calls

#app/controllers/users_controller.rb
class UsersController < ApplicationController
def custom
@city = City.find params[:city_id]
respond_to do |format|
format.js
end
end
end

#app/views/users/custom.coffee
$('.a').append("<%=j render 'users/customTemplate' %>");

上面是“后端”。这是“前端”:

#app/views/users/_form.html.erb (removed HTML to clean it up for this)
<%= form_for(@user, remote: true) do |f| %>
<%= f.text_field :name %>
<%= f.collection_select :city_id, City.order(:name), :id, :name, include_blank: true %>
<%= f.submit %>
<% end %>

#app/assets/javascripts/users.coffee
$(document).on 'change', '#user_city_id', (evt) ->
$.ajax '/cities/' + $(this).val() + '/update',
type: 'GET'
dataType: 'html'
data: {
city_id: $('#user_city_id :selected').val()
}
error: (jqXHR, textStatus, errorThrown) ->
console.log("AJAX Error: #{textStatus}")
success: (data, textStatus, jqXHR) ->
console.log("Dynamic country select OK!")

看完这个你会收获很多Railscast :

enter image description here

关于ruby-on-rails - Ruby on Rails 中的动态选择菜单,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/32868378/

24 4 0
Copyright 2021 - 2024 cfsdn All Rights Reserved 蜀ICP备2022000587号
广告合作:1813099741@qq.com 6ren.com