Model Relations
Favorite :
class Favorite < ActiveRecord::Base
belongs_to :favoritable, polymorphic: true
belongs_to :user, inverse_of: :favorites
end
User :
class User < ActiveRecord::Base
has_many :favorites, inverse_of: :user
end
, , :
class Category < ActiveRecord::Base
has_many :favorites, as: :favoritable
end
, favorites.
, , :
@user.favorites << Favorite.new(favoritabe: Category.find(1))
, Favorite @user.favorites, favoritable. favoritable Favorite.
, , Rails :
@user.favorites.build(favoritable: Category.find(1))
, - :
@user.favorites.where(favoritable_type: 'Category') # get favorited categories for user
Favorite.where(favoritable_type: 'Category') # get all favorited categories
, , :
class Favorite < ActiveRecord::Base
scope :categories, -> { where(favoritable_type: 'Category') }
end
:
@user.favorites.categories
, @user.favorites.where(favoritable_type: 'Category') .
, , , , , - @user.favorites.categories. Favorite:
class Favorite < ActiveRecord::Base
belongs_to :favoritable, polymorphic: true
belongs_to :user, inverse_of: :favorites
validates :user_id, uniqueness: {
scope: [:favoritable_id, :favoritable_type],
message: 'can only favorite an item once'
}
end
, user_id, favoritable_id favoritable_type. favoritable_id favoritable_type , , user_id favoritable. , , " - ".
, , _id _type. Rails , , . .
, db/schema.rb. favorites : :
add_index :favorites, :favoritable_id
add_index :favorites, :favoritable_type
.
, , . user_id favorites. , , .
, : , , . :
add_index :favorites, [:favoritable_id, :favoritable_type], unique: true
, , , , , , -.