Rails - Polymorphic Favorites (user can like different models)

We are trying to add a few favorable objects where the user can like many different objects, but are not sure how to make it work.

Here is a favorite model:

class Favorite < ActiveRecord::Base
  # belongs_to :imageable, polymorphic: true
  belongs_to :user
  belongs_to :category
  belongs_to :business
  belongs_to :ad_channel
  belongs_to :location
  belongs_to :offer
end

User Model:

class User < ActiveRecord::Base
  has_many :favorites, as: :favoritable
end

And one example model of what can be beneficial:

class Category < ActiveRecord::Base
  has_many :sub_categories
  has_many :ad_channels
  has_many :offers
  belongs_to :favoritable, polymorphic: true
end

I'm not sure if this is configured correctly, so this will be the first thing we need some feedback on.

Secondly, how do we “love” something for the user?

This is what we have tried so far unsuccessfully:

@user.favorites << Category.find(1)

EDIT: And for this you need a favorites table table? This is a fairly new concept for us.

+3
source share
1 answer

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))  # add favorite for user

, 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

, , , , , , -.

+14

All Articles