【问题标题】:How to fetch the last child record group by parent ID with matched conditions如何通过匹配条件的父 ID 获取最后一个子记录组
【发布时间】:2012-04-20 13:08:30
【问题描述】:

我在我的项目中使用 meta_search gem,并且有用户和 user_details 表。

users 表应该包含不可更改的信息,例如姓名、性别、血型、出生日期等

user_details 有地址、手机号...等

用户.rb

has_many :user_details

user_detail.rb

belongs_to :user

我将每个更新的 user_details 记录视为新记录。 我目前正在将 user_details 的最后一条记录显示为用户的当前记录

user_details 表的样子

id name       gender   phone        user_id
1. xxx        m        99389989     1
2  xxx        f        3344444      1
3  xxx        m        323434       1
4  xxx yy     f        3324324      2
5  xxx yyy    f        332423       2

问题:当我使用关键字搜索时,如何获取每个匹配条件的用户的最后一条 user_details 记录。

示例:如果我搜索 name_starts_with 'xxx' 那么它正在获取 ID 1 到 5。但我只想获取 ID 3 和 5

提前致谢

【问题讨论】:

    标签: ruby-on-rails-3 gem meta-search


    【解决方案1】:

    我终于用mysql的MAX方法修复了

    scope :last_record_in_each_group, lambda { |name|
      cond = "user_details.id in (select max(user_details.id) from user_details group by user_details.user_id)"
      cond << " and upper((CONCAT(first_name,' ', middle_name,' ', last_name))) like ?"
      {:conditions => [cond, "%#{name.upcase}%"]}
    }
    

    在视图中

    <%= search.text_field :last_record_in_each_group, :placeholder => "User Name" %>
    

    【讨论】:

      猜你喜欢
      • 2020-10-01
      • 2020-12-25
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      • 2012-01-23
      相关资源
      最近更新 更多