ruby on rails - Unable to get has_many through working properly - incorrect object counts returned -


i'm still new rails, forgive me if i'm missing obvious issue. current project involves users able post, delete, like, , unlike bookmarks. on user's profile page, there listing of bookmarks user has posted, , list of bookmarks have liked. i've been trying set more elegant solution collecting "liked bookmarks" instead of using .pluck in below code.

# inside users_controller.rb def show     @user_bookmarks = current_user.bookmarks.all     @liked_bookmarks = bookmark.where(id: current_user.likes.pluck(:bookmark_id)) end 

relationships each model:

# inside user.rb has_many :bookmarks has_many :likes, dependent: :destroy  # inside bookmark.rb belongs_to :user has_many :likes, dependent: :destroy  # inside like.rb belongs_to :user belongs_to :bookmark 

i received suggestion instead set has_many through relationship, so:

# inside user.rb has_many :bookmarks has_many :likes, dependent: :destroy has_many :bookmarks, through: :likes, as: :liked_bookmarks  # inside users_controller.rb def show     @user_bookmarks = current_user.bookmarks.all     @liked_bookmarks = current_user.liked_bookmarks.all end 

which makes sense me, cannot work (liked_bookmarks not recognized method) , unable discover i'm missing.

i fired rails c try understand issue, , reset user model , controller original code. when type following correct results based on database entries:

user = user.first user.bookmarks.count # returns 4 (correct) user.bookmarks.where(id: user.likes.pluck(:bookmark_id)).count # returns 2 (correct) 

however, when designate has_many through relationship...

# user.rb has_many :bookmarks has_many :likes, dependent: :destroy has_many :bookmarks, through: :likes    # <-- liked_bookmarks still failed, removed curiousity 

...here's same commands return now:

user = user.first user.bookmarks.count # returns 2 (incorrect) user.bookmarks.where(id: user.likes.pluck(:bookmark_id)).count # returns 2 (correct) 

after examining objects returned in above 2 lines, they're both returning bookmarks liked.

# 'likes' table contains: t.integer  "user_id" t.integer  "bookmark_id" 

i'd return correct number of objects in original code has_many through relationship using liked_bookmarks designation. can let me know i'm missing? have been going wrong way?

i'm using rails 4.1.8 , ruby 2.1.2p95

your second has_many :bookmarks, through: likes overriding first has_many :bookmarks.

to fix issue, instead of has_many :bookmarks, through: :likes, as: :liked_bookmarks, use:

has_many :liked_bookmarks, through: :likes, source: :bookmark

and can call user.liked_bookmarks.count

more info on source in so answer


Comments

Popular posts from this blog

android - MPAndroidChart - How to add Annotations or images to the chart -

javascript - Add class to another page attribute using URL id - Jquery -

firefox - Where is 'webgl.osmesalib' parameter? -