Hi All,
I am learning rails at the moment and have gone through one of the
tutorials on the rails website for creating a simple blog system.
I have added some new features to it and it is working great.
However, I would like to show someone my code and see if it is the right
or
most efficient way of achieve this.
This system is based on the blog system from the Getting Started with
Rails
guide which can be found on
I simply added a rank up/rank down function to the blog system:
First, in my routes.rb I added:
resources :articles do
resources :comments
member do
get ‘rankup’
get ‘rankdown’
end
end
Then, in my controller I added two new actions:
def rankup
@this_article = Article.find(params[:id])
@new_rank = @this_article.rank.to_i-1
@prev_article = Article.find_by(rank: @new_rank)
@prev_article.rank = @this_article.rank
@this_article.rank = @new_rank
@this_article.save
@prev_article.save
redirect_to articles_path
end
def rankdown
@this_article = Article.find(params[:id])
@new_rank = @this_article.rank.to_i+1
@next_article = Article.find_by(rank: @new_rank)
@next_article.rank = @this_article.rank
@this_article.rank = @new_rank
@this_article.save
@next_article.save
redirect_to articles_path
end
I also updated the destroy action to include a re ranking function:
def destroy
@article = Article.find(params[:id])
@start_rank = @article.rank
@next_articles = Article.where([“rank > ?”, @start_rank]).order(‘rank
ASC’)
@next_articles.each do |article|
article.rank = @start_rank
article.save
@start_rank = @start_rank + 1
end
@article.destroy
redirect_to articles_path
end
And in the view I simply added the links to the list:
<% @articles.each.with_index do |article, index| %>
<%= article.title %>
<%= article.text %>
<%= article.rank %>
<%= link_to ‘View’, article_path(article) %>
<%= link_to ‘Edit’, edit_article_path(article) %>
<%= link_to ‘Delete’, article_path(article), method: :delete,
data: {confirm: ‘Are you sure?’} %>
<% if index != 0 %>
<%= link_to ‘Up’, rankup_article_path(article) %>
<% end %>
<% if index != @articles.count-1 %>
<%= link_to ‘Down’, rankdown_article_path(article) %>
<% end %>
<% end %>
As mentioned, I am new to RoR so I don’t know if I’m doing this
correctly
according the Rails convention but the code is working great so I’m
happy
about that.
If someone can review my code please and tell me what I can improve on,
that would be great.
I’m also thinking there might be an existing gem or something that I can
install that will do the ranking for me automatically.
Anyway, look forward to your feedbacks.
Thanks in advance.