Skip to content

Commit 42563ab

Browse files
committed
preserve order of has_many field values - closes #9
1 parent 301e4c2 commit 42563ab

File tree

2 files changed

+13
-5
lines changed

2 files changed

+13
-5
lines changed

app/assets/javascripts/kms_models/application/controllers/entries_controller.coffee.erb

Lines changed: 6 additions & 5 deletions
Original file line numberDiff line numberDiff line change
@@ -27,8 +27,9 @@ EntriesController = ($scope, $state, Restangular, $stateParams, Alertify, Errors
2727

2828
$scope.initAssociationField = (field)->
2929
if field.type == 'Kms::HasManyField'
30-
$scope.entry.values[field.liquor_name] = _.filter $scope[field.liquor_name], (element)->
31-
_.contains $scope.entry.values[field.liquor_name], element.id.toString()
30+
fieldEntries = _.map $scope.entry.values[field.liquor_name], (entryId)->
31+
_.find $scope[field.liquor_name], { 'id': parseInt(entryId) }
32+
$scope.entry.values[field.liquor_name] = _.compact fieldEntries
3233
else
3334
$scope.entry.values[field.liquor_name] = _.find $scope[field.liquor_name], (element)->
3435
$scope.entry.values[field.liquor_name] == element.id.toString()
@@ -65,16 +66,16 @@ EntriesController = ($scope, $state, Restangular, $stateParams, Alertify, Errors
6566
if $scope.entry.slug
6667
fd.append("entry[slug]", $scope.entry.slug)
6768
for key, value of $scope.entry.values
68-
continue if value == undefined
69-
if value
69+
# continue if value == undefined
70+
unless _.isEmpty(value)
7071
if value.constructor.name == 'Array'
7172
for element in value
7273
id = if element.constructor.name == 'Object' then element.id else element
7374
fd.append("entry[values][#{key}][]", id)
7475
else if value.constructor.name != 'Object'
7576
fd.append("entry[values][#{key}]", value || '')
7677
else
77-
fd.append("entry[values][#{key}]", value || '')
78+
fd.append("entry[values][#{key}]", if value? then value else '')
7879
$scope.entry.withHttpConfig({ transformRequest: angular.identity }).post('', fd, '', {"Content-Type": undefined}).then ->
7980
$state.go('models.entries', modelId: $scope.model.id)
8081
,(response)->

app/models/kms/has_many_field.rb

Lines changed: 7 additions & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -3,6 +3,13 @@ class HasManyField < Field
33
def get_value(entry)
44
entry_ids = entry.values[liquor_name]
55
association_records = Kms::Entry.where(id: entry_ids)
6+
if entry_ids.present?
7+
# this one allows ORDER BY the IN value list like this example:
8+
# SELECT * FROM "comments" WHERE ("comments"."id" IN (1,3,2,4))
9+
# ORDER BY id=1 DESC, id=3 DESC, id=2 DESC, id=4 DESC
10+
order_sql = entry_ids.map {|entry_id| "id=#{entry_id} DESC"}
11+
association_records = association_records.order(order_sql.join(','))
12+
end
613
Liquor::DropDelegation.wrap_scope(association_records)
714
end
815
end

0 commit comments

Comments
 (0)