【问题标题】:Formatting DDL values populated from DB格式化从 DB 填充的 DDL 值
【发布时间】: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 %>

【问题讨论】:

    标签: ruby-on-rails database


    【解决方案1】:

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

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

    在你的情况下,

    options_from_collection_for_select(@categories, :name, :id)
    

    See the documentation

    【讨论】:

    • 感谢您的帮助!
    • 没问题,很高兴能帮上忙!您应该将其中一个答案标记为已接受的解决方案,以便其他人可以看到解决您的问题并从中受益。
    【解决方案2】:

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

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

    更多信息:here

    【讨论】:

      猜你喜欢
      • 1970-01-01
      • 2012-03-14
      • 2017-10-08
      • 1970-01-01
      • 2014-09-05
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      • 2019-08-27
      相关资源
      最近更新 更多