繁体   English   中英

将字符串转换为Rails中的整数

[英]Convert string into integer in 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

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!
    ...

暂无
暂无

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM