0

私は次のものを持っています (Voteとの多態的な関連付けとして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).

votes.find_by_user_id(current_user.id)投稿ビューと投票コントローラーの両方を次のように置き換えたいと思います。

  def vote_by_current_user
    self.votes.find_by_user_id(current_user.id)
  end

したがって、次のように読みやすくなります。

@vote = @votable.vote_by_current_userまた<% if @post.vote_by_current_user.polarity == 1 %>

そのメソッドを両方で利用できるようにする方法がよくわかりません。

助言がありますか?

4

1 に答える 1

1

1 つのこと: モデルのセッションに関連することは何もしないでください (MVC パターンを壊します)。そのため、既に正しい方法で行っています。

これを改善するためにできることは、逆の方法を取ること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

複数のクエリを避けるために、呼び出しによって返されたリレーションを保存することを忘れないでください:

 <% if vote = current_user.polarized_vote_for( @post ) %>
   <%= form_for [@post, vote] do |f| %>
     # etc.
于 2012-12-02T10:23:06.303 に答える