Skip to content
New issue

Have a question about this project? Sign up for a free GitHub account to open an issue and contact its maintainers and the community.

By clicking “Sign up for GitHub”, you agree to our terms of service and privacy statement. We’ll occasionally send you account related emails.

Already on GitHub? Sign in to your account

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

Open
wants to merge 1 commit into
base: master
Choose a base branch
from

Conversation

chumakoff
Copy link

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
Projects
None yet
Development

Successfully merging this pull request may close these issues.

1 participant