获取与给定参数匹配的rails记录,这些参数最接近不同记录的升序

时间:2016-07-08 20:47:06

标签: ruby-on-rails activerecord

给出一个模型:

the_model
    :string_one
    :string_two
    :boolean_flag
    :other_fields_I_can't_use_to_search

并且鉴于我已经有一个该模型的记录

model id: 12, string_one: "test 1", string_two: "test 2", boolean_flag: false

有没有办法用相同的字符串参数获取模型的记录,并且最接近初始记录的不同标志是按升序搜索的?

我需要最接近的一个,因为这些记录成对出现,但可以有多个对,所以我不能只搜索另一个匹配的

编辑:

示例数据库:

id: 1, string_one: "test1", string_two: "test2":, boolean_flag: false
id: 2, string_one: "test3", string_two: "test4":, boolean_flag: false
id: 3, string_one: "test1", string_two: "test2":, boolean_flag: true
id: 4, string_one: "test5", string_two: "test6":, boolean_flag: false
id: 5, string_one: "test1", string_two: "test2":, boolean_flag: false
id: 6, string_one: "test3", string_two: "test4":, boolean_flag: true
id: 7, string_one: "test1", string_two: "test2":, boolean_flag: true
id: 8, string_one: "test5", string_two: "test6":, boolean_flag: true
id: 9, string_one: "test1", string_two: "test2":, boolean_flag: false
id: 10, string_one: "test1", string_two: "test2":, boolean_flag: true

我需要找到记录7的对,在这种情况下是记录5。 我不需要记录9或记录1

1 个答案:

答案 0 :(得分:0)

我认为您应该可以使用模型中的方法实现此目的:

the_model
  def nearest_pair
   self.class.where(string_one: string_one, string_two: string_two, boolean_flag: !boolean_flag).order(id: :asc).first
# by default AR#first would order by the primary key column(id) in ascending order though
  end

希望能回答你的问题。