将字符串转换成整数的轨道

问题描述 投票:-1回答:2

我创建一个的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-rails ruby-on-rails-5 form-for
2个回答
1
投票

如果你用插值空间分隔字符串,你可以试试这个。

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

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!
    ...
© www.soinside.com 2019 - 2024. All rights reserved.