【发布时间】:2016-11-01 06:03:42
【问题描述】:
菜鸟问题:我的基本 Rails 应用程序有一个包含类别和汤的数据库(是的,来自 Code School),类别类别包含许多汤。我正在为用户添加使用表单添加类别和汤的功能。为了添加新的汤,我希望用户能够从可用的数据库列表中分配一个类别。
我得到 3 个 DDL,而不是显示 3 个类别的 1 个下拉列表,每个显示 3 个值,例如 #<Category:0x007fbbdceb50db>。如何让正确的值出现在单个 DDL 中?类别有“id”和“name”值,而汤有“id”、“name”和“category_id”值。
感谢所有帮助。
categories_controller.rb
class CategoriesController < ApplicationController
def index
@categories = Category.all
end
def show
@categories = Category.find(params[:id])
end
def new
end
def create
@categories = Category.new(params.require(:categories).permit(:name))
@categories.save
redirect_to @categories
end
end
soups_controller.rb
class SoupsController < ApplicationController
before_action :fetch_soup, only: [:show, :edit, :update, :destroy, :toggle_feature]
def index
@soups = Soup.all
end
def show
@soups = Soup.find(params[:id])
end
def new
end
def create
@soups = Soup.new(params.require(:soups).permit(:name, :category_id))
@soups.save
redirect_to @soups
end
index.html.erb
<p>Add new soup</p>
<%= form_for :soups, url: soups_path do |f| %>
<p>
<%= f.label :Name %>
<%= f.text_field :name %>
</p>
<p>
<%= f.label :CategoryID %>
<% @categories.each do |category| %>
<%= f.select :category_id, options_for_select(@categories, 'name') %>
<% end %>
</p>
<p>
<%= f.submit %>
</p>
<% end %>
【问题讨论】: