开发者

Rails 3, where to put method?

Hey have method called voted? that sees if someone voted. Where would I put it so it can be used in both the c开发者_C百科ontroller and view? First thought about placing it in the Voting Records model but I can't call current_user there. Then the project helper, but it fails there as well?

def voted?(project)
   Project.votes.exists?( :project_id => project.id, :user_id => current_user.id )
end

Thanks


Have you considered this?

class User < ActiveRecord::Base
  has_many :votes # assuming you have this association
  def voted?(project)
    votes.exists?(:project_id => project)
  end
end

Now you can use the following anywhere, in controllers (keeping them skinny), in views keeping it neat.

current_user.voted?(project)


You should put it inside the User class. However: You should have it use the user_id of the user instance, rather than the current_user


put it in the helper for your model..

e.g. ./app/helpers/yourmodel_helper.rb

0

上一篇:

下一篇:

精彩评论

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

最新问答

问答排行榜