Ruby on Rails Tuesday, June 30, 2015

Hi All,

First of all, let me quickly clarify the meaning of ranking here.
All I'm doing is move an article up or down in the display on the index file.

Quick example. Below is a sample of the Articles table:

ID       title                                    ranking
5         Rails is cool                        1
6         Programming is fun            2
7         How to install Rails             3
8         Macbook Pro features        4

If a user click on article ID 7 to move it up, this is what the system should do:

Change the ranking for article ID 7 to 2
Change the ranking for article ID 6 to 3

Basically, swap them around.

So as you can see, when a user click on an article, the system needs to modify 2 records in the db.

Now, if I want to move the self.save to the controller, the best way I can think of the implement this is as follows:

IMPORTANT: I have renamed the column rank to ranking below

In my model, I have 3 methods:

def self.find_by_rank(id, rank)
  @this_article = find(id)

  if (rank == "up")
    @next_article = find_by(ranking: @this_article.ranking.to_i-1)
  else
    @next_article = find_by(ranking: @this_article.ranking.to_i+1)
  end
end

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

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

And in my controller, I have this:

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

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

  @this_article.save
  @affected_article.save

  redirect_to articles_path()
end

This is the best way I can think of the move the self.save to the controller while keeping the majority of the logic in the model.

Please let me know if there is a better way.

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/47a54481-78ec-4467-923d-bef5e5c6fb31%40googlegroups.com.
For more options, visit https://groups.google.com/d/optout.

No comments:

Post a Comment