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.
所以。我不是一个用户能够写一个以上的评论,所以我想检查供应商/:vendorId URL这是“显示”操作,并有办法进行“写评论”按钮消失或显示基于是否已为@current_user编写了针对该特定供应商的评论。
I know the @vendor.id and @loggedin_user.id but not sure how to do a find on two parameters.
我知道@ vendor.id和@ loggedin_user.id,但不知道如何对两个参数进行查找。
1 个解决方案
#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 => @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:
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?
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) %>
#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 => @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:
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?
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) %>