rmre icon indicating copy to clipboard operation
rmre copied to clipboard

Use column name to create associations

Open Techbrunch opened this issue 7 years ago • 0 comments

Currently it appears that the associations are created based on the foreign keys. It would be nice if it could do it also based on column name.

Quick & Dirty solution for me:

    def constraint_src(table_name, tables)
      constraints = []
      connection.columns(table_name).map(&:name).each do |column|
        puts column
        if column.include?('_id') and tables.include?(column.chomp('_id').pluralize)
          table = column.chomp('_id')
          constraints << "belongs_to :#{table.downcase.singularize}"
        end
      end

      tables.each do |table|
        if table != table_name
          connection.columns(table).map(&:name).each do |column|
            if column.include? '_id' and "#{table_name.singularize}_id" === column
              constraints << "has_many :#{table.downcase.singularize}"
            end
          end
        end
      end
      constraints
    end

Note this will fail to detect has_one associations.

Techbrunch avatar Jul 20 '17 12:07 Techbrunch