首页 > 解决方案 > 在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但没有用。

标签: ruby-on-railsruby-on-rails-5form-for

解决方案


如果你用空格分隔符插入一个字符串,你可以试试这个。

'1 one'.split(' ').first.to_i

推荐阅读