开发者

Determine if count of related model > 0

开发者 https://www.devze.com 2022-12-31 03:58 出处:网络
I have a model called Stem. I need a \'thumbs up\' feature, so I have created a second model called Thumb, which consists of stem_id and user_id.

I have a model called Stem. I need a 'thumbs up' feature, so I have created a second model called Thumb, which consists of stem_id and user_id.

I'm also using the restful authentication plugin for user credentials.

I have the 'thumbs up' button working, which adds a row to the thumbs table fine, but I'd like to be able to check if the currently logged in user has already given a thumbs up to this particular stem.

I tried adding this to the Stem model:

def thumbed
    Thumb.count_by_sql ["SELECT COUNT(*) FROM thumbs WHERE user_id = ? AND stem_id = ?", current_user.id, self.id ]
end

The problem here is that the stem model has no access to the current_user variable the the controllers have.

Is there a way I can get access to this property, or alternatively, is there another way I could go about checking this? I was hoping to get this as a property in the model because the stems are passed over to a 开发者_如何学编程Flex app using RubyAMF.

Thanks!


Your controller knows the current_user, and your Stem model probably shouldn't. You can, however clean up your code and avoid hard-wiring SQL with a named_scope and pass the user into that.

#thumb.rb
named_scope :for_user_id, lambda {|id| {:conditions => {:user_id => id}}}

#stem.rb
def thumbed_by_user(user)
  self.thumbs.for_user_id(user.id).count > 0
end


# some controller
stem = some_method_that_gets_a_stem
is_already_thumbed = stem.thumbed_by_user(current_user)


Can you pass the current user to thumbed? Where are you calling it from?

BTW, you could try to simplify all of this using associations. I'm not 100% sure I understand what you're trying to do, but it sounds like you have the following...

class Stem
  has_many :thumbs
end

class User
  has_many :thumbs
end

class Thumb
  belongs_to :user
  belongs_to :stem
end

Then you can use find though associations to get at your thumbs without resorting to direct SQL. Check out this RailsCast: http://railscasts.com/episodes/3-find-through-association


What ended up working for me first was something like this:

I added these methods to my stem model:

def thumbed_by? usr_id
  Thumb.count(:conditions => {:user_id => usr_id, :stem_id => self.id}) > 0
end

def owned_by? usr_id
  self.id == usr_id
end

I also added this:

attr_accessor :thumbed, owned

Then in my show action where these were needed, I added the following lines:

@stem.thumbed = @stem.thumbed_by? current_user.id
@stem.owned = @stem.owned_by? current_user.id

This works exactly how I would like (the Flex app is already interpreting it as properly), but is there a way I could shorten this?

0

精彩评论

暂无评论...
验证码 换一张
取 消