在Rails 6中,多个下拉菜单的实现通常涉及到表单构建和视图渲染。以下是一些基础概念和相关信息:
<select>
元素来实现,其中包含多个<option>
元素。假设我们有两个模型:Category
和Product
,并且每个Product
属于一个Category
。
# app/models/category.rb
class Category < ApplicationRecord
end
# app/models/product.rb
class Product < ApplicationRecord
belongs_to :category
end
在视图中创建一个表单,包含多个下拉菜单。
<!-- app/views/products/_form.html.erb -->
<%= form_with(model: product, local: true) do |form| %>
<% if product.errors.any? %>
<div id="error_explanation">
<h2><%= pluralize(product.errors.count, "error") %> prohibited this product from being saved:</h2>
<ul>
<% product.errors.full_messages.each do |message| %>
<li><%= message %></li>
<% end %>
</ul>
</div>
<% end %>
<div class="field">
<%= form.label :name %>
<%= form.text_field :name %>
</div>
<div class="field">
<%= form.label :category_id %>
<%= form.collection_select(:category_id, Category.all, :id, :name) %>
</div>
<div class="actions">
<%= form.submit %>
</div>
<% end %>
在控制器中处理表单提交。
# app/controllers/products_controller.rb
class ProductsController < ApplicationController
before_action :set_product, only: [:show, :edit, :update, :destroy]
def new
@product = Product.new
end
def create
@product = Product.new(product_params)
if @product.save
redirect_to @product, notice: 'Product was successfully created.'
else
render :new
end
end
private
def set_product
@product = Product.find(params[:id])
end
def product_params
params.require(:product).permit(:name, :category_id)
end
end
原因:可能是由于数据库查询失败或视图渲染错误。
解决方法:
原因:可能是由于参数验证失败或模型关联错误。
解决方法:
以下是一个完整的示例,展示了如何在Rails 6中实现多个下拉菜单:
# app/models/category.rb
class Category < ApplicationRecord
end
# app/models/product.rb
class Product < ApplicationRecord
belongs_to :category
end
# app/controllers/products_controller.rb
class ProductsController < ApplicationController
before_action :set_product, only: [:show, :edit, :update, :destroy]
def new
@product = Product.new
end
def create
@product = Product.new(product_params)
if @product.save
redirect_to @product, notice: 'Product was successfully created.'
else
render :new
end
end
private
def set_product
@product = Product.find(params[:id])
end
def product_params
params.require(:product).permit(:name, :category_id)
end
end
<!-- app/views/products/_form.html.erb -->
<%= form_with(model: product, local: true) do |form| %>
<% if product.errors.any? %>
<div id="error_explanation">
<h2><%= pluralize(product.errors.count, "error") %> prohibited this product from being saved:</h2>
<ul>
<% product.errors.full_messages.each do |message| %>
<li><%= message %></li>
<% end %>
</ul>
</div>
<% end %>
<div class="field">
<%= form.label :name %>
<%= form.text_field :name %>
</div>
<div class="field">
<%= form.label :category_id %>
<%= form.collection_select(:category_id, Category.all, :id, :name) %>
</div>
<div class="actions">
<%= form.submit %>
</div>
<% end %>
通过以上步骤和示例代码,你应该能够在Rails 6中成功实现多个下拉菜单。
领取专属 10元无门槛券
手把手带您无忧上云