R
R
Robert2015-07-14 14:39:25
Ruby on Rails
Robert, 2015-07-14 14:39:25

Organizing ActiveRecord links?

There are 3 models:

class Post < ActiveRecord::Base
  belongs_to :user
  has_many :likes, :dependent => :destroy
  has_many :users, through: :likes
end

class Like < ActiveRecord::Base
  belongs_to :user
  belongs_to :post	
end

class User < ActiveRecord::Base
  has_many :posts, :dependent => :destroy
  has_many :likes, :dependent => :destroy
  has_many :posts, through: :likes
end

Here's the problem:
When I try to get a list of a user's posts ( @user.posts), the script returns an array of liked posts. The same is true when deleting a user - only the "likes" of the user are deleted, but not the records of this user themselves.
How to remove this conflict of two associations and get the performance of both has_many and has_many :through ?

Answer the question

In order to leave comments, you need to log in

3 answer(s)
R
Robert, 2015-07-14
@Jowan

has_many :liked_posts, through: :likes, source: :article

T
thepry, 2015-07-14
@thepry

has_many :liked_posts, through: :likes, class_name: 'Post'

V
Viktor Vsk, 2015-07-14
@viktorvsk

The same is true when deleting a user - only the "likes" of the user are deleted, but not the entries themselves.

That is, if you wrote a post, I liked it, and then deleted my profile, then your work will sink into oblivion?

Didn't find what you were looking for?

Ask your question

Ask a Question

731 491 924 answers to any question