Permalink
Browse files

Merge pull request #1241 from Fivell/custom-foreign-keys

Fixed default_columns_for_object when object has non-standard foreign keys
  • Loading branch information...
2 parents 5abaa10 + 6118093 commit f0a3b1c2e69aa09d8fe4ad3796c3a313dec73ef6 @mikz mikz committed on GitHub Feb 15, 2017
Showing with 36 additions and 3 deletions.
  1. +1 −1 CHANGELOG.md
  2. +10 −1 lib/formtastic/helpers/inputs_helper.rb
  3. +16 −1 spec/helpers/inputs_helper_spec.rb
  4. +5 −0 spec/schema.rb
  5. +4 −0 spec/spec_helper.rb
View
@@ -1,5 +1,5 @@
## master
-
+ * Fixed default_columns_for_object when object has non-standard foreign keys (#1241)
* Fixed missing constants in production (#911)
* Removed support for Rails 3 and 4.0 (#1108)
* Removed deprecated input/action finder methods (#1139)
@@ -350,12 +350,21 @@ def association_columns(*by_associations) # @private
end
end
+ # Collects all foreign key columns
+ def foreign_key_columns # @private
+ if @object.present? && @object.class.respond_to?(:reflect_on_all_associations)
+ @object.class.reflect_on_all_associations(:belongs_to).map(&:foreign_key)
+ else
+ []
+ end
+ end
+
# Collects content columns (non-relation columns) for the current form object class.
def content_columns # @private
# TODO: NameError is raised by Inflector.constantize. Consider checking if it exists instead.
begin klass = model_name.constantize; rescue NameError; return [] end
return [] unless klass.respond_to?(:content_columns)
- klass.content_columns.collect { |c| c.name.to_sym }.compact
+ klass.content_columns.collect { |c| c.name.to_sym }.compact - foreign_key_columns
end
# Deals with :for option when it's supplied to inputs methods. Additional
@@ -398,7 +398,22 @@
it 'should not render timestamps inputs by default' do
expect(output_buffer).not_to have_tag('form > fieldset.inputs > ol > li.datetime')
end
-
+
+ context "with non-standard foregin keys" do
+ before do
+ @output_buffer = ''
+ end
+
+ it 'should respect foreign key while rendering select' do
+ concat(semantic_form_for(LegacyPost.new, {:url => '/'}) do |builder|
+ concat(builder.inputs)
+ end)
+ expect(output_buffer).to have_tag('form > fieldset.inputs > ol > li.select select#legacy_post_post_author', :count => 1)
+ expect(output_buffer).not_to have_tag('input#legacy_post_post_author')
+ end
+
+ end
+
context "with a polymorphic association" do
before do
View
@@ -13,4 +13,9 @@
t.datetime "updated_at"
end
+ #non-rails foreign id convention
+ create_table "legacy_posts", force: :cascade do |t|
+ t.integer "post_author", limit: 4, null: false
+ end
+
end
View
@@ -134,6 +134,10 @@ def name
end
end
+ class ::LegacyPost < ActiveRecord::Base
+ belongs_to :author, foreign_key: :post_author
+ end
+
class ::Continent
extend ActiveModel::Naming if defined?(ActiveModel::Naming)
include ActiveModel::Conversion if defined?(ActiveModel::Conversion)

0 comments on commit f0a3b1c

Please sign in to comment.