1

The answer on this question has provided me with a nice roadmap for how to generate select tags with data from a collection on an association.

This works nicely and everything is going great.

The issue I have now is, how do I handle an empty collection?

With the regular :type => :input, I can just specify :nil => "Some nil message here".

But that doesn't seem to work for the collection, and to make matters worse, when there is nothing in the collection it seems to be displaying some integers (i.e. 1 and 2). I am assuming those are the IDs from the previously displayed objects in the collection, but for obvious reasons that doesn't make much sense.

Any ideas on how I can handle an empty collection with this gem?

Thanks.

Edit 1:

One alternative is to just put my original best_in_place helper tag inside an if statement for when a collection is not nil. But then how does the user edit it when it is blank? Perhaps there may be no way to handle this, because it would involve creating a new record in the collection.

4

1 に答える 1

2

I use a "workaround" for the empty options in a select tag, it could help you:

:type => :select, :collection => @my_colletion || [[I18n.t('common.none'), -1]]

When @my_colletion is nil, it shows a choice named 'None' with id = -1 (wich is not that bad to handle in the backend).

This part of code assumes the @my_collection is an array of arrays like [ [key, value], [key, value], ... ] OR nil.

Although, if you want your MyModel.all collection to fit the conditions for best_in_place, you can use the following:

@my_collection = MyModel.all.map{ |object| [object.name, object.value] } 
# => this returns an array like [ [key, value], [key, value], ... ]
# => returns an empty array (NOT nil) if there is no entry in the DB

About the -1 id: Using the -1 id as 'none' is easy because you don't need to explicitly handle the value nil (tests, etc). With the -1 id, you can use the following:

MyModel.where(id: params[:id]).first # => Returns the first object that has the params[:id]
# if params[:id] is -1, it will return nil and not raise an error.

I hope it helped :)

于 2012-11-30T17:29:27.197 に答える