【问题标题】:How to translate find_by_sql statement into named_scope?如何将 find_by_sql 语句翻译成 named_scope?
【发布时间】:2010-05-24 21:51:49
【问题描述】:

如何将以下内容转换为 named_scope?

  def self.commentors(cutoff=0)
    return User.find_by_sql("select users.*, count(*) as total_comments from users, comments 
      where (users.id = comments.user_id) and (comments.public_comment = 1) and (comments.aasm_state = 'posted') and (comments.talkboard_user_id is null) 
      group by users.id having total_comments > #{cutoff} order by total_comments desc")
  end

这是我现在拥有的,但它似乎不起作用:

  named_scope :commentors, lambda { |count=0|
    { :select => "users.*, count(*) as total_comments",
      :joins => :comments,
      :conditions => { :comments => { :public_comment => 1, :aasm_state => 'posted', :talkboard_user_id => nil} },
      :group => "users.id",
      :having => "total_comments > #{count.to_i}",
      :order => "total_comments desc"
    }
  }

最终,这是有效的;

  named_scope :commentors, lambda { |*args|
      { :select => 'users.*, count(*) as total_comments',
        :joins => :comments,
        :conditions => { :comments => { :public_comment => 1, :aasm_state => 'posted', :talkboard_user_id => nil} },
        :group => 'users.id',
        :having => ['total_comments > ?', args.first || 0],
        :order => 'total_comments desc' }
      }  

【问题讨论】:

    标签: sql ruby-on-rails named-scope


    【解决方案1】:

    您遇到的问题是因为您将 users, comments 中的选择替换为 comments 的内部连接。要将 SQL 正确转换为 named_scope,请使用以下命令:

    named_scope :commentors, lambda { |cutoff|
        { :select => 'users.*, count(*) as total_comments',
          :conditions => { :comments => { :public_comment => 1, :aasm_state => 'posted', :talkboard_user_id => nil } },
          :from => 'users, comments',
          :group => 'users.id',
          :having => ['total_comments > ?', cutoff],
          :order => 'total_comments desc' } }
    

    而且你不能为 lambda 参数设置默认值,所以你不能使用|cutoff = 0|

    【讨论】:

    • 没有得到我期望的结果。 :talkboard_user_id => nil 的正确语法是什么?该字段必须为 nil 作为条件,但我想知道这是否是正确的语法?
    • 要设置默认值,我可以这样做吗? :have => ['total_cmets > ?', cutoff.nil? ? 0:截止]
    • {:field => nil} 是正确的语法,您必须发布完整的 SQL 查询以查看它为什么不符合该条件。
    • 问题不是问题,因为我尝试了这个条件语句:conditions => "(cmets.public_comment = 1) and (cmets.aasm_state = 'posted') and (cmets.talkboard_user_id is null) "
    • 你可以使用 cutoff.nil 吗? 0 : 有一个默认值的截止值,但每次使用它时都必须忍受警告而没有值。
    猜你喜欢
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 2011-01-01
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 2022-11-30
    • 1970-01-01
    相关资源
    最近更新 更多