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

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.

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!

Join the discussion

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

Join 53,406+ 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.

    Ruby on Rails tutorials, guides, and screencasts for web developers learning Ruby, Rails, Javascript, Turbolinks, Stimulus.js, Vue.js, and more. Icons by Icons8

    © 2021 GoRails, LLC. All rights reserved.