OK, so I have modified the code following Colin's suggestion.
Check it out:

In the controller, my action is as follows:

def rank
  @this_article = Article.find(params[:id])

  if (params[:rank] == 'up')
    @this_article.rankup(params[:rank])
  else
    @this_article.rankdown(params[:rank])
  end

  redirect_to articles_path()
end


In my model, I have rankup and rankdown instance methods then I have a 
private method:

def rankup(rank)
  swap_rank(self.id, self.ranking, rank)

  self.ranking = self.ranking - 1
  self.save
end

def rankdown(rank)
  swap_rank(self.id, self.ranking, rank)

  self.ranking = self.ranking + 1
  self.save
end

private

def swap_rank(id, ranking, rank)
  if (rank == 'up')
    @affected_article = Article.find_by(ranking: ranking.to_i-1)
    @affected_article.ranking = @affected_article.ranking + 1
  else
    @affected_article = Article.find_by(ranking: ranking.to_i+1)
    @affected_article.ranking = @affected_article.ranking - 1
  end

  @affected_article.save
end

I like this way. It is clean and simple.
All the code that make changes to the db resides in the model and the 
controller simply determines which model method to call.

Thanks, Colin.





-- 
You received this message because you are subscribed to the Google Groups "Ruby 
on Rails: Talk" group.
To unsubscribe from this group and stop receiving emails from it, send an email 
to [email protected].
To post to this group, send email to [email protected].
To view this discussion on the web visit 
https://groups.google.com/d/msgid/rubyonrails-talk/9975d22f-d735-4918-8548-ad2c610f99b4%40googlegroups.com.
For more options, visit https://groups.google.com/d/optout.

Reply via email to