how do I check if a 'Review' has already been written by a given @current_user?

how do I check if a 'Review' has already been written by a given @current_user?

心舞飞扬 发布于 2021-11-24 字数 654 浏览 792 回复 1 原文

For my model Vendor:

:has_many Review

And Each User:

:has_many Review

And Each Review:

:belongs_to Vendor
:belongs_to User

So. I don't one a User to be able to write more than one Review, so I want to do a check on the vendors/:vendorId URL which is the "show" action, and have a way to make the "Write Review" button disappear or appear based on whether for the @current_user there has already been written a Review for that specific Vendor.

I know the and but not sure how to do a find on two parameters.

如果你对这篇文章有疑问,欢迎到本站 社区 发帖提问或使用手Q扫描下方二维码加群参与讨论,获取更多帮助。



需要 登录 才能够评论, 你可以免费 注册 一个本站的账号。


青朷 2022-06-07 1 楼

There are lots of ways to do this. If you just want to find on two parameters, you can do:

Review.find(:first, :conditions => {:user_id =>, :vendor_id =>})

You can also make use of the associations, like the following:, :conditions => {:vendor => @vendor})

A named_scope would be another way:

class Review < ActiveRecord::Base
  named_scope :for_vendor, lambda {|vendor| 
    {:conditions => {:vendor => vendor}}
  belongs_to :vendor
  belongs_to :user

Since it's a business rule, I'd recommend encapsulating this logic in a method on either User or Vendor, like:

def can_review?(vendor), :conditions => {:vendor => @vendor}).nil?

You could then do, in the view:

<%= review_vendor_button if @current_user.can_review?(@vendor) %>