views:

32

answers:

1

Hello!

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 @vendor.id and @loggedin_user.id but not sure how to do a find on two parameters.

+1  A: 

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 => @user.id, :vendor_id => @vendor.id})

You can also make use of the associations, like the following:

@current_user.reviews.find(:first, :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
end

@current_user.reviews.for_vendor(@vendor).empty?

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)
  self.reviews.find(:first, :conditions => {:vendor => @vendor}).nil?
end

You could then do, in the view:

<%= review_vendor_button if @current_user.can_review?(@vendor) %>
Greg Campbell
this was good, thanks!
Angela