我正在创建一个form_for,其中一个字段从数据库中获取下拉列表。我要对数据进行插值以显示字符串,但我想将其ID存储回与表单链接的其他数据库中。
class FlightsController < ApplicationController
def new
@flight = Flight.new
@airplane = @flight.airplane
@options = Airport.list
end
def create
@flight = Flight.new(flight_params)
if @flight.save!
flash[:success] = "Flight created successfully."
redirect_to @flight
else
flash[:danger] = "Flight not created."
redirect_to :new
end
end
private
def flight_params
params.require(:flight).permit(:name, :origin, :destination, :depart, :arrive, :fare, :airplane_id)
end
end
<%= form_for(@flight) do |f| %>
...
<div class="row">
<div class="form-group col-md-6">
<%= f.label :origin %>
<%= f.select :origin, grouped_options_for_select(@options), { include_blank: "Any", class: "form-control selectpicker", data: { "live-search": true } } %>
</div>
</div>
...
<% end %>
class Airport < ApplicationRecord
def self.list
grouped_list = {}
includes(:country).order("countries.name", :name).each do |a|
grouped_list[a.country.name] ||= [["#{a.country.iso} #{a.country.name}", a.country.iso]]
grouped_list[a.country.name] << ["#{a.iata} #{a.name} (#{a.city}, #{a.country.name})", a.id]
end
grouped_list
end
end
class Flight < ApplicationRecord
belongs_to :origin, class_name: "Airport"
belongs_to :destination, class_name: "Airport"
belongs_to :airplane
has_many :bookings, dependent: :destroy
has_many :passengers, through: :bookings
end
显示以下错误,
Airport(#69813853361360) expected, got "43" which is an instance of String(#47256130076180)
在控制台中运行时,Airport.list
的输出如下所示:
=> {"India"=>[["IN India", "IN"], ["AGX Agatti Airport (Agatti, India)", 3], ["IXV Along Airport (Along, India)", 5], ["AML Aranmula International Airport (Aranmula, India)", 6], ["IXB Bagdogra International Airport (Siliguri, India)", 50]]}
Parameters: {"utf8"=>"✓", "authenticity_token"=>"+Z8+rkrJkkgaTznnwyTd/QjEoq3kR4ZmoUTp+EpM+320fNFg5rJm+Izx1zBODo/H7IIm3D+yg3ysnVUPmy7ZwQ==", "flight"=>{"name"=>"Indigo", "origin"=>"49", "destination"=>"11", "depart"=>"2019-02-21T21:30", "arrive"=>"2019-02-22T01:30", "fare"=>"2500", "airplane_id"=>"3"}, "commit"=>"Create Flight"}
我尝试使用to_i
,但是没有用。
答案 0 :(得分:1)
如果您要使用空格定界符对字符串进行插值,则可以尝试此操作。
'1 one'.split(' ').first.to_i
答案 1 :(得分:0)
grouped_options_for_select
发送a.id
作为字符串值。在您创建操作中将其转换为整数。
def create
@flight = Flight.new(flight_params)
@flight.origin = @flight.origin.to_i ## <== add this line
if @flight.save!
...