-
Notifications
You must be signed in to change notification settings - Fork 331
Custom Association Options
When ActiveScaffold displays a dropdown on the form of records to associate with the current record (the one being edited or created), it has to decide which records should be present. The default behavior is to display “orphaned” (unassociated) records for :has_one and :has_many associations, and to display all records for :belongs_to and :has_and_belongs_to_many. You may want to display all records every time, or you may want to impose extra conditions. The solution is to create a method called options_for_association_conditions
in your controller’s helper file. This method accepts an AssociationReflection object and returns SQL conditions (in any of the common formats).
This method is used in association columns with :select form_ui too.
For example, let’s say that you have a UsersController, and that a User has_and_belongs_to_many Roles. Let’s say that you don’t want to show the Admin Role as an option, unless the current user is an Admin. You’ve already got validation set up, but you just don’t want the option in the list. Here’s what you could do:
module UsersHelper
def options_for_association_conditions(association)
if association.name == :roles
['roles.id != ?', Role.find_by_name('admin').id] unless current_user.admin?
else
super
end
end
end