Ruby on Rails
Thursday, July 2, 2015
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.saveend
def rankdown(rank) swap_rank(self.id, self.ranking, rank)
self.ranking = self.ranking + 1 self.saveend
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.saveend
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 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/9975d22f-d735-4918-8548-ad2c610f99b4%40googlegroups.com.
For more options, visit https://groups.google.com/d/optout.
Subscribe to:
Post Comments (Atom)
No comments:
Post a Comment