Last active
August 6, 2018 18:56
-
-
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
This file contains hidden or bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
class CategoriesPlace < ApplicationRecord | |
belongs_to :place | |
belongs_to :category | |
validates :place, :category, presence: true | |
end |
This file contains hidden or bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
# 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 |
This file contains hidden or bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
# Controller params sample | |
def place_params | |
params.require(:place).permit( | |
:name, | |
:description, | |
categories_places_attributes: [ | |
:category_id | |
] | |
) | |
end |
This file contains hidden or bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
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 |
Author
zrod
commented
Aug 6, 2018
•
Sign up for free
to join this conversation on GitHub.
Already have an account?
Sign in to comment