On 2 July 2015 at 11:07, Federicko <fedomain@gmail.com> wrote:
> 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.
>
A few points.
What happens if params[:rank] is not specified or is not valid?
What would the effect be if self.save in rankup failed (a validation
failure for example), or the affected_article.save failed?
What would the affect be if your app or the server crashed between the
two saves? As I previously suggested wrap the whole thing in a
transaction in order to recover from this sort of problem. In order
to do that change swap_rank to do the complete operation including
both saves, possibly by passing it the two articles to be swapped.
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/CAL%3D0gLu8wSSx8F0SqUR6fBxnZb9XD%3DHX3LAHwppi5vDYiMj2Xw%40mail.gmail.com.
For more options, visit https://groups.google.com/d/optout.
No comments:
Post a Comment