Skip to content

Instantly share code, notes, and snippets.

@zrod
Last active August 6, 2018 18:56
Show Gist options
  • Save zrod/fb779d08dfae7a963fdf2e81507c249c to your computer and use it in GitHub Desktop.
Save zrod/fb779d08dfae7a963fdf2e81507c249c to your computer and use it in GitHub Desktop.
Saving (associating on new records) many-to-many relationships with Rails / active record
class CategoriesPlace < ApplicationRecord
belongs_to :place
belongs_to :category
validates :place, :category, presence: true
end
# Category model
class Category < ApplicationRecord
has_many :categories_places
has_many :places, through: :categories_places, dependent: :destroy
validates :name, presence: true
validates :description, presence: true
before_save do
self.slug = name.parameterize
end
end
# Controller params sample
def place_params
params.require(:place).permit(
:name,
:description,
categories_places_attributes: [
:category_id
]
)
end
class Place < ApplicationRecord
belongs_to :user
has_many :categories_places
has_many :categories, through: :categories_places
# This does the trick (Create new Place record and assign existing categories to it)
accepts_nested_attributes_for :categories_places
validates :name, presence: true
validates :description, presence: true
validates_associated :categories_places
before_save do
self.slug = name.parameterize
end
end
@zrod
Copy link
Author

zrod commented Aug 6, 2018

POST https://localhost/places
{
  "name": "Nameless",
  "description": "rails test",
  "categories_places_attributes": [
  	{ "category_id": 1 }
  ]
}

Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment