简体   繁体   中英

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 controller 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..

eg ./app/helpers/yourmodel_helper.rb

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM