首页 > 解决方案 > ActiveRecord 搜索类似条目以显示页面选择 (Rails 5)

问题描述

我有一个从一个非常大的数据库生成的显示页面,由@listing = Listing.find(params[:listing_id])控制器查询。在页面底部,我还有指向其他三个列表的链接;现在他们被 查询@listings = Listing.last(3),但我正在尝试选择三个类似的列表 - 按社区或价格范围。

例子 -Listing.where(:price => 500000..600000).limit(2)

但是......与活动页面列表相比,我不知道如何做到这一点。例如,我将如何从同一社区或同一记录的某个价格范围内挑选列表?如果有人可以指导我如何建立这种联系,我将不胜感激(我相当初级,但也正在真正学习享受 ActiveRecord,并希望扩展我可以用它做的事情)。

在有人问之前,这是我的架构:

 create_table "listings", force: :cascade do |t|
    t.string   "mls"
    t.datetime "created_at",     null: false
    t.datetime "updated_at",     null: false
    t.string   "community"
    t.string   "description"
    t.integer  "price"
    t.string   "status"
    t.string   "address"
  end

标签: ruby-on-railsactiverecordcontrollerrails-activerecord

解决方案


看起来你需要这样的东西:

price_range = (@listing.price - 100)..(@listing.price + 100)
Listing.where(price: price_range, community: @listing.community).limit(3)

你在正确的轨道上!


推荐阅读