Reputation: 55283
I have the following (Vote
as a polymorphic association with Post
) :
votes_controller.rb:
if already_voted?
@vote = @votable.votes.find_by_user_id(current_user.id)
@vote.destroy
end
posts/_vote_form.html.erb:
<div class="vote-form">
<% if @post.votes.exists?(:user_id => current_user.id) %>
<% if @post.votes.find_by_user_id(current_user.id).polarity == 1 %>
<%= form_for ([@post, @post.votes.find_by_user_id(current_user.id)]),
method: :delete,
remote: true do |f| %>
(etc).
I would like to replace votes.find_by_user_id(current_user.id)
in both post view and vote controller with something like this:
def vote_by_current_user
self.votes.find_by_user_id(current_user.id)
end
So they become more readeable like this:
@vote = @votable.vote_by_current_user
or <% if @post.vote_by_current_user.polarity == 1 %>
I'm not really sure how to make that method available on both of them.
Any suggestions?
Upvotes: 0
Views: 40
Reputation: 12564
one thing : you should not do anything related to the session in your models (it breaks the MVC pattern), so you're already doing it the right way.
What you can do to improve this is to take it the other way around : start from current_user
.
class User < ActiveRecord::Base
def self.polarized_vote_for( votable, polarity = 1 )
votes.where( polarity: polarity ).find_by_votable_id( votable.id )
end
just remember to store the relation returned by the call to avoid multiple queries :
<% if vote = current_user.polarized_vote_for( @post ) %>
<%= form_for [@post, vote] do |f| %>
# etc.
Upvotes: 1