Monday, June 6, 2011

how to find out data type of a column in a table through RoR code

In one of my application, there is a table, Product with more than 100 columns. I want to find out
- the data type of "product_owner" column
- to iterate over all columns and collect array of boolean / tinyint(1) data type columns.

Here is the code to do that:
Product.columns_hash["product_owner"].sql_type
Above code will give you the data type of the column, in this case its "varchar(255)"

If you know that "product_owner" is the 9th column of the table, then you can also find the data type by command:
Product.content_columns[9].sql_type

To iterate over all columns and collect array of boolean / tinyint(1) data type columns:
b= []
Product.content_columns.each do |p|
  if p.sql_type == "tinyint(1)"
    b << p.human_name
  end
end

Now, when you will print 'b', you will get array of all the fields of data type boolean / tinyint(1)

How to iterate over table columns and get values

In one of my application, there is a table, Product with more than 100 columns. I wanted to iterate over all the columns and display their values on product show page.

This is how I did it:
<table border="1">
    <% for column in Product.content_columns %>
        <tr>
          <th><%= column.human_name %></th> 
          <td><%= h @product.send(column.name) %> <td>
        </tr>
    <% end %>
</table>

column.human_name - Returns the human name of the column name. If your column is "product_owner", it will return "Product owner".

column.name will return the name of the column (product_owner)
@product.send(column.name) will return the value of the column.