zoukankan      html  css  js  c++  java
  • rails scope for rail3

     

    Rails 3 ambiguous column names and multiple order scopes

    no comments yet, post one now

    After updating a few apps to Rails 3 I came across some issues with the new scoping syntax.

    Ambiguous Column Names

    In one case I use a module to define some common scopes that are used across more than one model. I quickly came up against the ambiguous column name error (e.g. Column ‘created_at’ in order clause is ambiguous —from MySQL). To fix this I used the table_name prefix right in my scoping string. In general you should always do this anywhere you use strings in your scopes. For example;

    # remember to add the table_name to avoid ambiguous columns
    scope :recent, order("#{table_name}.created_at DESC")
    # or directly
    scope :recent, order("questions.created_at DESC")
    
    # you don't have to add the table_name when using a hash, Rails takes care of that!
    scope :by_user, lambda{|user| where(:user_id => user.id).recent}
    

    Multiple Order Scopes

    Another issue I found was combining multiple order scopes. In Rails 2 with named scopes this used to work as you’d expect. But combining multiple order scopes in Rails 3 seems to fail, only applying the last order scope to the query.

    # given the recent scope defined above, in this case we'd expect;
    scope :flagged, order(" #{table_name}.flag_count DESC").recent
    # to be 
    'ORDER BY questions.flag_count DESC, questions.created_at DESC'
    # BUT its not! instead its simply
    'ORDER BY questions.created_at DESC'
    # to order on multiple columns inside a scope, I have to duplicate my recent order scope like so
    scope :flagged, order(" #{table_name}.flag_count DESC, #{table_name}.created_at DESC").recent
    

    All in all, i’m very much in favour of the new syntax and AREL in general. It simplifies compounding queries together with additional scopes and delays their execution until it is needed.

    Some Rails 3 ActiveRecord Links

    about 1 month ago
  • 相关阅读:
    flex-grow带来的排版问题
    css文本样式,空格
    第八周作业
    JSON简介
    Ajax
    java applet小程序
    java ee 部分分析
    xml相关知识
    JAVA EE体系结构图
    java EE初次理解
  • 原文地址:https://www.cnblogs.com/lexus/p/1877063.html
Copyright © 2011-2022 走看看