Class: Uchi::Field::HasAndBelongsToMany
- Inherits:
-
Field
- Object
- Field
- Uchi::Field::HasAndBelongsToMany
- Defined in:
- app/components/uchi/field/has_and_belongs_to_many.rb
Defined Under Namespace
Constant Summary collapse
- DEFAULT_COLLECTION_QUERY =
->(query:) { query }.freeze
Instance Method Summary collapse
- #associated_repository(record:) ⇒ Object
- #collection(record:) ⇒ Object
-
#collection_query(query_proc = Configuration::Unset) ⇒ self, Proc
Sets or gets a custom query for filtering the collection of associated records.
- #group_as(_action) ⇒ Object
-
#initialize(name) ⇒ HasAndBelongsToMany
constructor
A new instance of HasAndBelongsToMany.
-
#param_key ⇒ Object
Returns the key to use for this field in params.
- #permitted_param ⇒ Object
Constructor Details
#initialize(name) ⇒ HasAndBelongsToMany
Returns a new instance of HasAndBelongsToMany.
89 90 91 92 |
# File 'app/components/uchi/field/has_and_belongs_to_many.rb', line 89 def initialize(name) super @collection_query = DEFAULT_COLLECTION_QUERY end |
Instance Method Details
#associated_repository(record:) ⇒ Object
70 71 72 73 74 75 76 77 |
# File 'app/components/uchi/field/has_and_belongs_to_many.rb', line 70 def associated_repository(record:) reflection = record.class.reflect_on_association(name) model = reflection.klass repository_class = Uchi::Repository.for_model(model) raise NameError, "No repository found for associated model #{model}" unless repository_class repository_class.new(context: repository.context) end |
#collection(record:) ⇒ Object
79 80 81 82 83 84 85 86 87 |
# File 'app/components/uchi/field/has_and_belongs_to_many.rb', line 79 def collection(record:) query = associated_repository(record: record).find_all Uchi::CallWithFlexibleArguments .new(@collection_query) .call( context: repository.context, query: query ) end |
#collection_query(query_proc = Configuration::Unset) ⇒ self, Proc
Sets or gets a custom query for filtering the collection of associated records.
When called with an argument, sets the query and returns self for chaining. When called without arguments, returns the current query.
111 112 113 114 115 116 |
# File 'app/components/uchi/field/has_and_belongs_to_many.rb', line 111 def collection_query(query_proc = Configuration::Unset) return @collection_query if query_proc == Configuration::Unset @collection_query = query_proc self end |
#group_as(_action) ⇒ Object
118 119 120 |
# File 'app/components/uchi/field/has_and_belongs_to_many.rb', line 118 def group_as(_action) :associations end |
#param_key ⇒ Object
Returns the key to use for this field in params
123 124 125 |
# File 'app/components/uchi/field/has_and_belongs_to_many.rb', line 123 def param_key association.association_foreign_key.pluralize.to_sym end |
#permitted_param ⇒ Object
127 128 129 |
# File 'app/components/uchi/field/has_and_belongs_to_many.rb', line 127 def permitted_param {param_key => []} end |