Rails Model find where not equal

前端 未结 6 1376
孤街浪徒
孤街浪徒 2020-12-07 14:29

How can I find records in my database on a not equal condition? I have this now, but is there a fancy rails-speak way of doing it?

GroupUser.where(\'user_id         


        
6条回答
  •  爱一瞬间的悲伤
    2020-12-07 14:55

    In Rails 4.x (See http://edgeguides.rubyonrails.org/active_record_querying.html#not-conditions)

    GroupUser.where.not(user_id: me)
    

    In Rails 3.x

    GroupUser.where(GroupUser.arel_table[:user_id].not_eq(me))
    

    To shorten the length, you could store GroupUser.arel_table in a variable or if using inside the model GroupUser itself e.g., in a scope, you can use arel_table[:user_id] instead of GroupUser.arel_table[:user_id]

    Rails 4.0 syntax credit to @jbearden's answer

提交回复
热议问题