Ruby on Rails Monday, June 29, 2015

Hi Fred,

I took your advice and tried to move the ranking logic over to the model. 
I've also consolidated the 2 actions.

Here's what I got:

In the controller:

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

  if (params[:rank] == 'up')
  @next_article = Article.find_by(rank: @this_article.rank.to_i-1)

  @this_article.rankup
  @next_article.rankdown
else
  @next_article = Article.find_by(rank: @this_article.rank.to_i+1)

  @this_article.rankdown
  @next_article.rankup
end

  @this_article.save
  @next_article.save

  redirect_to articles_path
end

In the view, I am passing in the query string rank to indicate whether we are ranking up or down.

And in my model I added two new methods:

def rankup
  self.rank = self.rank - 1
end

def rankdown
  self.rank = self.rank + 1
end

I've added the rank up / rank down as a method in the Article object. However, the key to my ranking logic is to first find the next record as I need to swap the ranking with the current record. So the code to finding the next record (either previous or next record depending on whether we are ranking up or down). This code can only reside in the controller as far as I can tell.

Please let me know if there is more code I can move to the model.

Thank you. 


--
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 rubyonrails-talk+unsubscribe@googlegroups.com.
To post to this group, send email to rubyonrails-talk@googlegroups.com.
To view this discussion on the web visit https://groups.google.com/d/msgid/rubyonrails-talk/95a528c4-37ae-4a23-83b3-329aab76d471%40googlegroups.com.
For more options, visit https://groups.google.com/d/optout.

No comments:

Post a Comment