Ruby on Rails数组没有返回结果

时间:2016-04-06 06:22:10

标签: ruby-on-rails ruby

以下是我在控制器中的查询:

@cref = Creference.where("lower(name) LIKE ?", "#{@city.downcase}")

  if @cref.present?
    cities_array = @cref.map {|con| "%#{con.countries}%" } 
    #cities_array return --> ["%["Kuching", "Kota Kinabalu"]%"]
    @products.where("city ILIKE ANY ( array[?] )", cities_array) --> []
end

product尽管在产品表中有名称具有上述名称的城市,但不会返回任何结果。谢谢!

SCHEMA

产物:

create_table "products", force: :cascade do |t|
    t.integer  "user_id"
    t.string   "name"
    t.integer  "payment_type",        limit: 2
    t.datetime "created_at",                    precision: 6,             null: false
    t.datetime "updated_at",                    precision: 6,             null: false
    t.integer  "product_category_id"
    t.integer  "location_id"
    t.text     "description"
    t.text     "highlight"
    t.integer  "price_cents"
    t.integer  "zip"
    t.string   "country"
    t.string   "state"
    t.string   "city"
    t.string   "address"
    t.string   "apt"
    t.integer  "refund_day"
    t.string   "currency"
    t.integer  "refund_percent"
    t.integer  "refundable",          limit: 2,               default: 0
    t.integer  "step",                limit: 2,               default: 0
    t.integer  "discount",                                    default: 0
    t.string   "slug"
    t.integer  "status",              limit: 2,               default: 1
    t.integer  "verification",        limit: 2,               default: 0
  end

creference:

  create_table "creferences", force: :cascade do |t|
    t.string   "name"
    t.string   "countries",  default: [],              array: true
    t.datetime "created_at",              null: false
    t.datetime "updated_at",              null: false
  end

2 个答案:

答案 0 :(得分:2)

你可以这样做:

@cref = Creference.where("lower(name) LIKE ?", "#{@city.downcase}")

  if @cref.present?
    cities_array = @cref.collect {|con| con.countries }.flatten 
    #cities_array will return --> ["Kuching", "Kota Kinabalu"]
    @products.where("city IN (?)", cities_array) 
    # the IN query will find the city names that are in the cities_array
    # but in that case your product tables city name should be in lowercase
    # as you are fetching lowercase city names from Creference
end

N.B。我没有测试过上面的代码。但它应该工作。 :)

答案 1 :(得分:0)

首先,检查User.limit(1).offset(params[:offset].present? ? params[:offset] : 0) 的值以查看返回的内容。

其次,尝试在语句末尾附加cities_array并打印它以查看sql的样子:

to_sql

最后但并非最不重要的是,puts @products.where("city ILIKE ANY ( array[?] )", cities_array).to_sql 看到您的表中确实有产品:)。