I’ve been trying to write a method that effectively displays the result
of a find() for say… my Customer model.
What i’ve come up with is this:
- The controller
My main controller first makes the query via the model
class MainController < ApplicationController
def index
order = [‘lastname’,‘firstname’,‘father’,‘address1’, …
,‘insuranceid’]
@customers = Customer.find_customers(order) #passes the columns in
the order
#we want them shown
#Without this (using
attributes)
#the attributes method
returned
#the columns in random
order!
@order = order #also passes them to the
view
end
end
- The Customer model
class Customer < ActiveRecord::Base
def self.find_customers(order)
selection =""
order.each do |column|
selection += column+"," # appends members of the order array to the
string
end
resultset = find(:all, :select => [selection.chop]) #queries the DB
resultset #returns the array of Customer objects limited by :select
end
end
- The view
<% columns_number = @order.length %>
<%=Customer.table_name%> | |
---|---|
<%=column%> | <%end%>|
<%=customer.send(value)%> | <% end %>
My objective is to make a view method that renders ANY type of object
array or ANY other object type for that matter. The standard scaffold
method doesn’t work for me because it uses “for column in
Customer.content_columns” which are the columns defined in the model,
ALL of them, whereas I limit the columns via :select.
Since I’m a newbie Ruby/Rails coder I’m almost certain there’s a better
way to make such a “scaffold-like” view that can render any array of db
objects. Could anybody contribute to this code an help improve it? Is
there a more “rails” way to do what I’m trying to do?