All threads / How do I check if a model inside a model has been liked?
Ask A Question


You’re not receiving notifications from this thread.

How do I check if a model inside a model has been liked?

Tolase Kelvin Adegbite asked in Rails

Hello there! I implemented likes to my app using this tutorial I went a little bit different route though. I have PollItem < Poll. Poll has_many :poll_items and only poll_items can be liked.

How do I check if a poll item has been liked within the polls model so that only one of it can be liked.. The plan is to hide the like button once the check is true.

Hey Tolase,

Assuming your poll_items are scoped to your polls and your likes are scoped to your poll_items you can scope your likes to your polls by adding the following to your polls model:

has_many :likes, through :poll_items

then this will work as expected:

def likes?(poll)
poll.likes.where(user_id: id).any?

Hope that helps!

Join the discussion

Want to stay up-to-date with Ruby on Rails?

Join 70,078+ developers who get early access to new tutorials, screencasts, articles, and more.

    We care about the protection of your data. Read our Privacy Policy.

    logo Created with Sketch.

    Screencast tutorials to help you learn Ruby on Rails, Javascript, Hotwire, Turbo, Stimulus.js, PostgreSQL, MySQL, Ubuntu, and more. Icons by Icons8

    © 2023 GoRails, LLC. All rights reserved.