【问题标题】:rails belongs_to with select_tagrails belongs_to 和 select_tag
【发布时间】:2014-01-23 09:39:37
【问题描述】:

我已经将模型“Timetableap”与“Aircompany”模型关联起来

     class Timetableap < ActiveRecord::Base
        belongs_to :aircompany
      ...
     end


  class Aircompany < ActiveRecord::Base
     has_many :timetableaps
     ...
   end

在“时间表”控制器中:

  class TimetableapsController < ApplicationController
   ...
   def index
     @t = Timetableap.search(params[:search_ap],params[:search_al])
   ...
   end

我的结构表 “航空公司”表

  create_table "aircompanies", :force => true do |t|
     t.string   "iata_code",        :null => false
     t.string   "icao_code",        :null => false
     t.string   "awb_prefix"
     t.string   "airline_name",     :null => false
     t.integer  "airport_id",       :null => false
     t.string   "country"
     t.string   "ap_hubs"
     t.date     "start"
     t.date     "end"
     t.datetime "created_at",       :null => false
     t.datetime "updated_at",       :null => false
   end

“时间表”表

  create_table "timetableaps", :force => true do |t|
     t.integer  "Flight_Number"
     t.integer  "aircompany_id"
     t.integer  "way_start"
     t.integer  "way_end"
     t.string   "TermStart"
     t.string   "GateStart"
     t.string   "TermEnd"
     t.string   "GateEnd"
     t.string   "TypeOfPlane"
     t.time     "TimeStart"
     t.time     "TimeEnd"
     t.date     "DateOfStartNav"
     t.date     "DateOfEndNav"
     t.integer  "s1"
     t.integer  "s2"
     t.integer  "s3"
     t.integer  "s4"
     t.integer  "s5"
     t.integer  "s6"
     t.integer  "s0"
     t.integer  "e1"
     t.integer  "e2"
     t.integer  "e3"
     t.integer  "e4"
     t.integer  "e5"
     t.integer  "e6"
     t.integer  "e0"
     t.datetime "created_at",     :null => false
     t.datetime "updated_at",     :null => false
   end

如何在带有“aircompany.airline_name”的视图中显示下拉列表?

 <%= select_tag "search_al", options_from_collection_for_select(@t.group("aircompany_id"),"aircompany_id", **"aircompany"**), prompt: "All Airlines" %>

【问题讨论】:

    标签: ruby-on-rails ruby select belongs-to html-select


    【解决方案1】:

    目前尚不清楚您是否想要所有航空公司的下拉菜单,或者是否应该以某种方式过滤它们。

    如果您想要所有航空公司,这可行:

    <%= select_tag "search_al", options_from_collection_for_select(Aircompany.all, :id, :airline_name), prompt: "All Airlines" %>
    

    由于@t 似乎是Timetableap 记录的集合,您可以选择仅显示在当前时间表集合中找到的航空公司:

    <%= select_tag "search_al", options_from_collection_for_select(@t.map(&:aircompany).uniq, :id, :airline_name), prompt: "All Airlines" %>
    

    【讨论】:

    • 它不是一个哈希,它是一个数组。如果您希望它按Aircompany#airline_name 排序,这将起作用:@t.map(&amp;:aircompany).uniq.sort_by(&amp;:airline_name)
    猜你喜欢
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 2011-02-06
    • 1970-01-01
    • 1970-01-01
    • 2014-10-01
    相关资源
    最近更新 更多