Rails itself already has an idea of which database columns it considers
user visible: ActiveRecord.content_columns. As it is, I have a
different understanding/need of what ought to be visible to the user.
Specifically, in my opinion, lock_version is nothing a user ever needs
to see, but on the other hand, columns containing foreign keys contain
something where the user at least wants to see a derivative. In all,
nothing a small amount of coding cannot mend.
So here it goes:
my_content_columns = content_columns + association_columns -
[ ''lock_version'' ]
def association_columns
assocs = reflect_on_all_associations
return [] unless assocs
assoc_columns = []
assocs.each do |assoc|
next unless assoc.macro == :belongs_to
name = assoc.options[:foreign_key]
if name.nil?
name = Inflector.underscore(
assoc.options[:class_name] || assoc.name) + ''_id''
end
assoc_columns << name
end
assoc_columns.map { |ac| columns.find { |c| c.name == ac } }
end
Well, apparently it works, at least in the cases I''ve thought of. The
trouble is that I am not sure that I''ve thought of all the relevant
cases and this kind of code feels awfully brittle. I''d much rather get
the same result with Rails''s on-board means if they exist.
Michael
--
Michael Schuerig The more it stays the same,
mailto:michael-q5aiKMLteq4b1SvskN2V4Q@public.gmane.org
The less it changes!
http://www.schuerig.de/michael/ --Spinal Tap, The Majesty of Rock