【问题标题】:how do I check if a 'Review' has already been written by a given @current_user?如何检查给定的@current_user 是否已经写过“评论”?
【发布时间】:2009-04-28 06:26:37
【问题描述】:

对于我的模型供应商:

:has_many Review

每个用户:

:has_many Review

每条评论:

:belongs_to Vendor
:belongs_to User

所以。我没有一个用户可以写多个评论,所以我想检查 vendor/:vendorId URL 这是“显示”操作,并有办法进行“写评论”按钮消失或出现取决于@current_user 是否已经为该特定供应商撰写了评论。

我知道@vendor.id 和@loggedin_user.id 但不确定如何查找两个参数。

【问题讨论】:

    标签: ruby-on-rails


    【解决方案1】:

    有很多方法可以做到这一点。如果你只想找到两个参数,你可以这样做:

    Review.find(:first, :conditions => {:user_id => @user.id, :vendor_id => @vendor.id})
    

    您还可以使用关联,如下所示:

    @current_user.reviews.find(:first, :conditions => {:vendor => @vendor})
    

    named_scope 是另一种方式:

    class Review < ActiveRecord::Base
      named_scope :for_vendor, lambda {|vendor| 
        {:conditions => {:vendor => vendor}}
      }
      belongs_to :vendor
      belongs_to :user
    end
    
    @current_user.reviews.for_vendor(@vendor).empty?
    

    由于这是一个业务规则,我建议将此逻辑封装在 User 或 Vendor 的方法中,例如:

    def can_review?(vendor)
      self.reviews.find(:first, :conditions => {:vendor => @vendor}).nil?
    end
    

    然后你可以在视图中做:

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

    【讨论】:

      猜你喜欢
      • 1970-01-01
      • 1970-01-01
      • 2021-12-23
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      • 2012-07-07
      相关资源
      最近更新 更多