Ask A Question

Notifications

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 https://gorails.com/episodes/liking-posts. 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.

Reply

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?
end

Hope that helps!

Reply
Join the discussion
Create an account Log in

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

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

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