代码之家  ›  专栏  ›  技术社区  ›  Lazlo

无法使用实例变量从字符串数组返回数组元素

  •  0
  • Lazlo  · 技术社区  · 3 年前

    我有一个模型,其中一列是字符串数组

      create_table "shows", force: :cascade do |t|
        t.time "st"
        t.time "ed"
        t.integer "money"
        t.string "av_seats", default: "--- []\n"
        t.string "oc_seats", default: "--- []\n"
        t.datetime "created_at", precision: 6, null: false
        t.datetime "updated_at", precision: 6, null: false
        t.integer "theatre_id"
        t.integer "screen_id"
        t.integer "movie_id"
        t.index ["movie_id"], name: "index_shows_on_movie_id"
        t.index ["screen_id"], name: "index_shows_on_screen_id"
        t.index ["theatre_id"], name: "index_shows_on_theatre_id"
      end
    

    我在试着参考 av_seats oc_seats 在另一个模型的控制器中,通过此逻辑

    def create
        @booking = Booking.new(booking_params)
        @av_seats = Show.find(params[:show_id]).pluck(:av_seats)
        @oc_seats = Show.find(params[:show_id]).pluck(:oc_seats)
    
        if @booking.save
          if @av_seats.include? @booking.seat
            @oc_seats << @booking.seat
            @av_seats.delete @booking.seat
          end
          render json: @booking, status: :created, location: @booking
    

    本质上,它应该将一个元素从一个数组移动到另一个数组,并根据输入从上一个数组中删除相同的元素。

    "status": 404,
        "error": "Not Found",
        "exception": "#<ActiveRecord::RecordNotFound: Couldn't find Show without an ID>",
    

    我试过使用 pluck 方法,然后尝试使用 find 但我可能也做得不对。

        @av = Show.pluck(:show_id, :av_seats)
        @oc = Show.pluck(:show_id, :oc_seats)
    
        @av_seats = Show.find(@av)
        @oc_seats = Show.find(@oc)
    
    # routes.rb
    
    Rails.application.routes.draw do
      resources :movies
      resources :bookings
      resources :shows
      resources :screens
      resources :theatres
      resources :users
    end
    

    这就是表单的典型外观。这是一个API,所以没有视图,只有纯JSON。

    {
        "booking": {
            "user_id": 1,
            "show_id": 2,
            "screen_id": 2,
            "seat": "A5"
        }
    }
    
    0 回复  |  直到 3 年前
        1
  •  1
  •   Pascal    3 年前

    你创造了一个 Booking 资源 信息(:show_id)嵌套在 :bookings 输入你的爱人

    我想你是用了下面的方法 BookingsController

    def booking_params
      params.require(:booking).permit(:show_id, :user_id, :seat, :screen_id)
    end
    

    ?

    如果你的 预订 关联设置正确吗

    class Booking < ApplicationRecord
      belongs_to :show
    end
    

    然后你可以像这样进入节目:

    booking = Booking.new(booking_params)
    show = booking.show
    

    如果未设置关联,则可以使用

    show = Show.find(params[:booking][:show_id])
    # or
    show = Show.find(booking_params[:show_id]) # not _params_
    

    由于show对象是以任何方式加载的,因此您只需访问 av_seats oc_seats 直接地

    show.av_seats
    show.oc_seats
    

    pluck 这是一个优化,其中只有列 从数据库中获取。

    你可能想换个位置 xx_seats 列的类型为 string[] (与 array: true 在您的迁移中)。

    更改座椅阵列的内容后,需要保存放映记录。