query

An article by Gaspard Bucher

dynamic query building from params or other attributes

  1. action
  2. ajax
  3. API
  4. classes
  5. common attributes
  6. conditions
  7. context
    1. ancestors
    2. author
    3. comments
    4. comments_to_publish
    5. content_for_layout
    6. context
    7. count
    8. data
    9. each
    10. each_group
    11. expand_with
    12. find
    13. group
    14. node
    15. project
    16. proposed
    17. query
    18. query_errors
    19. query_parse
    20. real_project
    21. real_section
    22. redactions
    23. replies
    24. search_results
    25. section
    26. tags
    27. to_publish
    28. unknown
    29. user
    30. visitor
    31. visitor_node
  8. dates
  9. display
  10. forms
  11. i18n
  12. meta
  13. SQLiss
  14. urls

dynamic query building from params or other attributes

  • default (query used when no parameter is given)
  • eval RubyLess to access query (default = params[:qb])
  • select RubyLess string to access query
see New scope index, query_parse, introduction, zena 1.0

This method can be used to dynamically compile queries depending on params or other contextual elements.

You should not use this instead of context. The compilation is slower and has to be made on every request.

Usage example:

params[:qb]

Use the default params[:qb] as pseudo sql:

<ul do='query' default='nodes in project'>
  <li do='each' do='link'/>
</ul>

select

Using dynamic ‘select’ string as pseudo sql:

<ul do='query' select='pages in #{params[:scope] || \"project\"}' default='pages in project'>
  <li do='each' do='link'/>
</ul>

The default query is used to get the new context inside the query block (do we have a Page, a Contact, ...).

eval

Finally, you can use any RubyLess evaluated expression as source for the pseudo sql:

<ul do='query' eval='stored_qb' default='pages in project'>
  <li do='each' do='link'/>
</ul>

This example uses the value in a “stored_qb” property as pseudo sql. The “stored_qb” property has to be defined in the virtual class definition.

Error reporting

If an error occurs during the query, the field “query_errors” will contain the error message. A common idiom is therefore:

<ul do='query' eval='stored_qb' default='pages in project'>
  <li do='each' do='link'/>
  <li do='elseif' test='query_errors' do='query_errors'/>
  <li do='else' do='t'>nothing found</li>
</ul>