Skip to content

Add option to specify custom method for has_many relationships creation - #1386

Open
chumakoff wants to merge 1 commit into
JSONAPI-Resources:masterfrom
chumakoff:add_has_many_association_append_method_option
Open

Add option to specify custom method for has_many relationships creation #1386
chumakoff wants to merge 1 commit into
JSONAPI-Resources:masterfrom
chumakoff:add_has_many_association_append_method_option

Conversation

@chumakoff

Copy link
Copy Markdown

Currently has_many relations are added to a parent record via ActiveRecord's collection<< method. And there is no way to change that.

  • collection<< doesn't always work for complex associations (especially for using through option)
  • collection<< doesn't provide full control and confidence
  • collection<< silently ignores invalid records
  • customizing collection<< on model level (which is now the only workaround) for API purposes is not a good way

So, there should be a way to specify (and implement on API level) a custom method that appends has_many relationships.

Example

# post_resource.rb

has_many :tags, create_method: :add_tag

def add_tag(tag)
  @model.post_tags.create!(tag: tag) if @model.acceptable_tag?(tag)
end
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment

Labels

None yet

1 participant