【问题标题】:Is there a rails gem to use a single table for all of the "options" in multiple select inputs throughout an app?是否有一个 rails gem 可以为整个应用程序中的多个选择输入中的所有“选项”使用单个表?
【发布时间】:2011-03-17 08:24:58
【问题描述】:

因此,有时您只需要一个选项列表供您选择。是否有一个简单的 gem 可以让您轻松使用一个表格来处理您的应用中可能拥有的所有类型的选项?

此表可能如下所示:

id  | type   | value  | label
01  | color  | red    | Red
02  | color  | black  | Black
03  | shape  | circle | Circle
04  | shape  | square | Square
05  | state  | texas  | Texas

例如,国家列表、州列表、颜色列表、月份列表等...

那么当使用 select 时:

select_tag :color, options_for_colors

然后它会使用选项表中的值/标签填充选择,其中行的类型为 :color。

这很容易让我自己推出,但如果它已经建成,我不想花时间。

更新

我希望这是一个动态表,因此最终用户可以从选择选项表中添加/删除项目

【问题讨论】:

    标签: ruby-on-rails select input gem sti


    【解决方案1】:

    我一直用这个方法,

    app/models/user.rb

    ROLES = %w[admin author normal]
    

    app/views/users/_form.html.erb

    <%= f.collection_select :role, User::ROLES, :to_s, :titleize %>
    

    【讨论】:

    • 谢谢,这很简洁,但我正在寻找更有活力的东西。
    【解决方案2】:

    从 Rails 3.2 开始,这是我在初始化程序中所做的:

    ActiveRecord::Base.class_eval do
      def self.types
        Rails.application.routes.routes.select do |r|
          r.defaults[:action]=="index" && r.defaults[:controller]== self.name.to_s.downcase.pluralize
        end.map do |r|
          r.defaults[:type]
        end.compact
      end
    end
    

    在 routes.rb 中,我将 STI 操作映射到父模型的控制器,因为我精通控制器:

      resources :derived_models, :controller => :base_model, :type => "DerivedModel"
      resources :more_derived_models, :controller => :base_model, :type => "MoreDerivedModel"
    

    现在,Model.types 会给你["DerivedModel", "MoreDerivedModel"]

    【讨论】:

    • 这看起来只是给你一个 STI 子类的列表?不知道它如何回答最初的问题:(也许我错过了什么?
    • 嗯,它是列出选项的“单表”解决方案,或者我误解了你的意图。
    猜你喜欢
    • 2011-10-31
    • 1970-01-01
    • 1970-01-01
    • 2021-05-23
    • 1970-01-01
    • 2019-09-23
    • 2022-09-28
    • 1970-01-01
    • 1970-01-01
    相关资源
    最近更新 更多