Note that there are some explanatory texts on larger screens.

plurals
  1. PORails 3 - Ajax and controller refactor
    primarykey
    data
    text
    <p>I'm new to Rails and I'd like to know if I could refactor the following code.</p> <p>Basically I want to vote_down ou vote_up for a question in ajax.</p> <p>Controller :</p> <pre><code>def vote_up @question = get_question params[:id] if current_user != @question.user render :json =&gt; @question.vote(current_user, 'up').to_json end end def vote_down @question = get_question params[:id] if current_user != @question.user render :json =&gt; @question.vote(current_user, 'down').to_json end end </code></pre> <p>Model :</p> <pre><code>def vote(user, vote) if user.voted?(self) 'Question already voted' else I18n.t('question.voted') if user.send("#{vote}_vote", self) end end </code></pre> <p>View :</p> <pre><code>&lt;script&gt; $('#question_vote_up').live('ajax:success', function(evt, data, status, xhr) { $('#question_vote_up').remove() $('#question_vote_down').remove() alert(xhr.responseText) }) $('#question_vote_down').live('ajax:success', function(evt, data, status, xhr) { $('#question_vote_up').remove() $('#question_vote_down').remove() alert(xhr.responseText) }) &lt;/script&gt; &lt;% if current_user != @question.user %&gt; &lt;%= link_to t('question.vote_up'), { :action =&gt; "vote_up" }, :id =&gt; "question_vote_up", :remote =&gt; true %&gt; &lt;%= link_to t('question.vote_down'), { :action =&gt; "vote_down" }, :id =&gt; "question_vote_down", :remote =&gt; true %&gt; &lt;% end %&gt; </code></pre> <p>I can't figure out how don't repeat myself and if there is a cleaner way to </p> <pre><code>if current_user != @question.user </code></pre> <p>Thanks in advance </p>
    singulars
    1. This table or related slice is empty.
    1. This table or related slice is empty.
    plurals
    1. This table or related slice is empty.
    1. This table or related slice is empty.
    1. This table or related slice is empty.
    1. This table or related slice is empty.
    1. This table or related slice is empty.
 

Querying!

 
Guidance

SQuiL has stopped working due to an internal error.

If you are curious you may find further information in the browser console, which is accessible through the devtools (F12).

Reload