有很多方法可以做到这一点。如果你只想找到两个参数,你可以这样做:
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) %>