Column/Attribute names for a model
Posted by michael.schaerfer on 23-Jul-08 at 20:06
A quick way to get all column/attribute names for a model:
(normal columns are Strings, association-attributes are Symbols)
1 # returns all columns/attributes for a model 2 # column-names used for associations (foreign_keys) are replaces by their 3 # association-names (as symbol). 4 def get_column_names_for( record ) 5 # get all column-names, check for foreign_keys and replace them by association_name 6 record.columns.collect(&:name).collect { |c| 7 (a = check_association( record, c ) ).empty? ? c : a.collect(&:name) 8 }.flatten.uniq + 9 # get all has_one/has_many/habtm association names 10 record.reflect_on_all_associations.select { |a| a.macro.to_s =~/^has/ }.collect(&:name) 11 12 end 13 14 15 def check_association( record, string ) 16 # check if +string+ (like "artist_id") is a foreign_key for an association 17 # if yes, return association. 18 record.reflect_on_all_associations.select { |a| a.options[:foreign_key] ? 19 a.options[:foreign_key].to_sym == string.to_sym : 20 a.name.to_s.foreign_key.to_sym == string.to_sym } 21 end
Useful if you want to build like an automatic scaffold function or ...

Comments
There are 0 comments on this post. Post yours →
Post a comment
Required fields in bold.