Only call order when the given association responds to it.

Fixes #966.

This check is necessary because the given association may not respond to `order`.
This commit is contained in:
Lauro Caetano 2014-03-31 15:18:52 -03:00
parent 855ee4c904
commit 8e0d5ba799
3 changed files with 40 additions and 2 deletions

View File

@ -186,7 +186,13 @@ module SimpleForm
options[:collection] ||= options.fetch(:collection) {
conditions = reflection.options[:conditions]
conditions = conditions.call if conditions.respond_to?(:call)
reflection.klass.where(conditions).order(reflection.options[:order])
relation = reflection.klass.where(conditions)
if reflection.respond_to?(:order)
relation.order(reflection.options[:order])
else
relation
end
}
attribute = case reflection.macro

View File

@ -146,6 +146,15 @@ class AssociationTest < ActionView::TestCase
end
end
test 'builder does not call order if the given association does not respond to it' do
with_association_for @user, :pictures
assert_select 'form select.select#user_picture_ids'
assert_select 'form select[multiple=multiple]'
assert_select 'form select option[value=1]', 'Picture 1'
assert_select 'form select option[value=2]', 'Picture 2'
assert_select 'form select option[value=3]', 'Picture 3'
end
test 'builder creates a select with multiple options for collection associations' do
with_association_for @user, :tags
assert_select 'form select.select#user_tag_ids'

View File

@ -19,6 +19,27 @@ Relation = Struct.new(:all) do
alias_method :to_a, :all
end
Picture = Struct.new(:id, :name) do
extend ActiveModel::Naming
include ActiveModel::Conversion
class << self
delegate :where, to: :_relation
end
def self._relation
Relation.new(all)
end
def self.all
(1..3).map { |i| new(i, "#{name} #{i}") }
end
def persisted?
true
end
end
Company = Struct.new(:id, :name) do
extend ActiveModel::Naming
include ActiveModel::Conversion
@ -53,7 +74,7 @@ class User
:delivery_time, :born_at, :special_company_id, :country, :tags, :tag_ids,
:avatar, :home_picture, :email, :status, :residence_country, :phone_number,
:post_count, :lock_version, :amount, :attempts, :action, :credit_card, :gender,
:extra_special_company_id
:extra_special_company_id, :pictures, :picture_ids
def self.build(extra_attributes = {})
attributes = {
@ -133,6 +154,8 @@ class User
Association.new(Company, association, :belongs_to, { conditions: { id: 1 } })
when :extra_special_company
Association.new(Company, association, :belongs_to, { conditions: proc { { id: 1 } } })
when :pictures
Association.new(Picture, association, :has_many, {})
end
end