ruby-on-rails - 在rails中将字符串转换为整数
问题描述
我正在创建一个 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
但没有用。
解决方案
如果你用空格分隔符插入一个字符串,你可以试试这个。
'1 one'.split(' ').first.to_i
推荐阅读
- selenium-webdriver - Protractor:Protractor 中的 ignoreSynchronization 和 async/await 有什么区别
- node.js - 如何在 GraphQL 中获取相同的嵌套对象
- python - 降低 seaborn 线图上日期的 x 轴值密度
- xcode - 在 Ubuntu 上下载 MACOS VMWARE 并运行 Xcode 时遇到的问题
- javascript - 如何阻止超脚本覆盖我的输入?佩里尔
- python - Pyinstaller 无法执行脚本:FileNotFoundError:没有文件或目录:'C:\\Users\\etc'
- python - 没有这样的元素:使用 Selenium 和 Python 单击按钮时无法定位元素错误
- c# - 如何根据字符串的高度和宽度绘制矩形(作为背景)?
- go - 如何在 golang 中创建一个指定路径的空文件。假设在 $HOME/newFile.txt
- javascript - document.execCommand 有哪些替代方法来选择和复制文本?