格式化从DB

时间:2016-10-31 19:13:18

标签: ruby-on-rails database

noob问题:我的基本Rails应用程序有一个包含Categories和Soups的数据库(是的,来自Code School),类别包含许多Soups。我添加了用户使用表单添加Categories和Soups的功能。为了添加新的Soups,我希望用户能够从可用的DB列表中分配一个Category。

我没有显示3个类别的1个下拉列表,而是获得3个DDL,每个DDL显示3个值,如#<Category:0x007fbbdceb50db>。如何在单个DDL中显示正确的值?类别有&#34; id&#34;和&#34;名称&#34;值虽然汤有&#34; id&#34;,&#34; name&#34;,&#34; category_id&#34;值。

感谢您的帮助。

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 %>

2 个答案:

答案 0 :(得分:0)

您需要使用知道如何获取ActiveRecord模型集合并将其转换为DDL选项的options_from_collection_for_select助手。

您需要传递(1)集合(2)用于选项值的方法和(3)用于选项ID的方法。

在你的情况下,

options_from_collection_for_select(@categories, :name, :id)

See the documentation

答案 1 :(得分:0)

请尝试使用collection_select。它看起来像这样:

<%= collection_select(:soup, :category_id, Categories.all, :id, :name, prompt: "Select the category") %>

更多信息:here