【问题标题】:Rails select and orderRails 选择和订购
【发布时间】:2011-06-19 01:46:48
【问题描述】:

我正在尝试从关联中选择列计数,但它似乎不起作用。这是我的代码:

scope :search, lambda { |search, order_syntax|
    select("*, COUNT(payment_notifications.p_type) AS number_of_objects")
    {
      :conditions =>
      ['items.title LIKE ? OR items.desc LIKE ? OR taggings.context LIKE ?', "%#{search}%", "%#{search}%", "%#{search}%"],
      :include => [:taggings, :payment_notifications, :user],
      :order => 'number_of_objects'
    }
  }      

我想要实现的是: 我想按购买数量订购。所以,假设这是我的 payment_notifications 表:

item_id | p_type

2 | '付款'

2 | '付款'

6 | '付款'

2 | '付款'

3 | '付款'

6 | '付款'

无 | '退出'

顺序应该是这样的: 2 6 3

希望你能理解。

提前致谢。

【问题讨论】:

  • 什么不起作用?另外,您使用的是 Rails 2 还是 3?
  • Rails 3. 它给出了错误“未知列 number_of_objects”。我认为我需要一个全新的代码,因为我认为我的代码甚至不能满足我的需要。

标签: ruby-on-rails associations


【解决方案1】:

找到我的解决方案。需要使用计数器缓存。谢谢大家!

【讨论】:

    【解决方案2】:

    您还应该在订单块中包含 itme_id

    :order => 'item_id,number_of_objects'
    

    【讨论】:

    • 代码不起作用,我想我需要一个全新的代码,因为我的代码甚至不能满足我的需求。
    【解决方案3】:

    首先,您应该使用普通方法而不是范围,因为查询相当复杂,结果将完全相同(只是更易于格式化)。

    其次,当你不在任何地方使用它时,我不确定为什么你在那个 lambda 中有一个参数“order_syntax”。

    这是我的建议(使用新的 Active Record 链接语法)。我尚未对其进行测试,但如果我理解您的原始查询,它应该可以工作。

    def search(term)
      select("*, COUNT(payment_notifications.p_type) AS number_of_objects").
        where('items.title LIKE ? OR items.desc LIKE ? OR taggings.context LIKE ?', "%#{term}%", "%#{term}%", "%#{term}%").
          includes(:taggings, :payment_notifications, :user).
            order('number_of_objects')
    end
    

    【讨论】:

    • 同样的错误:SQLite3::SQLException: 没有这样的列:number_of_objects: SELECT DISTINCT "items".id FROM "items" LEFT OUTER JOIN "taggings" ON "taggings"."taggable_id" = "items "."id" AND "taggings"."taggable_type" = 'Item' 左外连接 "payment_notifications" ON "payment_notifications"。"item_id" = "items"."id" 左外连接 "users" ON "users"。 "id" = "items"."user_id" WHERE "items"."visible" = 't' AND (items.title LIKE '%%' OR items.desc LIKE '%%' OR taggings.context LIKE '%% ') ORDER BY number_of_objects LIMIT 10 OFFSET 0
    猜你喜欢
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 2011-08-03
    • 2017-02-24
    • 2013-12-21
    • 1970-01-01
    相关资源
    最近更新 更多