preload associations if possible
This commit is contained in:
parent
402ee26a26
commit
9113f56848
|
@ -156,7 +156,7 @@ module SimpleForm
|
|||
when :belongs_to
|
||||
reflection.options[:foreign_key] || :"#{reflection.name}_id"
|
||||
when :has_one
|
||||
raise ":has_one association are not supported by f.association"
|
||||
raise ":has_one associations are not supported by f.association"
|
||||
else
|
||||
if options[:as] == :select
|
||||
html_options = options[:input_html] ||= {}
|
||||
|
@ -167,6 +167,12 @@ module SimpleForm
|
|||
:"#{reflection.name.to_s.singularize}_ids"
|
||||
end
|
||||
|
||||
# Force the association to be preloaded for performance.
|
||||
if options[:preload] != false && object.respond_to?(association)
|
||||
target = object.send(association)
|
||||
target.to_a if target.respond_to?(:to_a)
|
||||
end
|
||||
|
||||
input(attribute, options.merge(:reflection => reflection))
|
||||
end
|
||||
|
||||
|
|
|
@ -585,6 +585,26 @@ class FormBuilderTest < ActionView::TestCase
|
|||
end
|
||||
end
|
||||
|
||||
test 'builder caches given association' do
|
||||
value = @user.company
|
||||
value.expects(:to_a).returns(value)
|
||||
with_association_for @user, :company
|
||||
assert_select 'form select.select#user_company_id'
|
||||
assert_select 'form select option[value=1]', 'Company 1'
|
||||
assert_select 'form select option[value=2]', 'Company 2'
|
||||
assert_select 'form select option[value=3]', 'Company 3'
|
||||
end
|
||||
|
||||
test 'builder does not cache given association if preload false' do
|
||||
value = @user.company
|
||||
value.expects(:to_a).never
|
||||
with_association_for @user, :company, :preload => false
|
||||
assert_select 'form select.select#user_company_id'
|
||||
assert_select 'form select option[value=1]', 'Company 1'
|
||||
assert_select 'form select option[value=2]', 'Company 2'
|
||||
assert_select 'form select option[value=3]', 'Company 3'
|
||||
end
|
||||
|
||||
# ASSOCIATIONS - BELONGS TO
|
||||
test 'builder creates a select for belongs_to associations' do
|
||||
with_association_for @user, :company
|
||||
|
|
|
@ -66,7 +66,7 @@ class ActionView::TestCase
|
|||
:age => 19,
|
||||
:amount => 15,
|
||||
:attempts => 1,
|
||||
:company => 1
|
||||
:company => [1]
|
||||
}.merge(options))
|
||||
|
||||
@other_validating_user = OtherValidatingUser.new({
|
||||
|
|
Loading…
Reference in New Issue