Rendering most recent articles rails 4 -


its listing oldest articles @ top , want opposite. think need order created_at somewhere have yet make work. know easy i'm still newbie. thanks

currently have

<div class="bit-75"> 
<h2 id="title"><%= link_to article.title, article_path(article) %></h2> <br>  <ul id="article-links">   <div id="article-image"><%= image_tag article.image_url %></div>   <br>   <li id="article-text"><%= article.text %></li> <br> <%= article.created_at %> <br>  <% if admin_signed_in? %>   <li><%= link_to 'edit',           edit_article_path(article) %></li>   <li><%= link_to 'destroy',        article_path(article),                 method: :delete, data: { confirm: 'are sure?'} %></li>   <li><%= link_to 'new article', new_article_path %></li> <% else %>                   <li><%= link_to 'make comment', article_path(article) %></li>               </ul> <% end %>    

article.rb

   class article < activerecord::base    has_many :comments, dependent: :destroy    validates :title, presence: true,                 length: { minimum: 5 }    mount_uploader :image, imageuploader                      end 

articles controller

def new  @article = article.new end  def index  @article = article.all end  def create    @article = article.new(article_params)    if @article.save   redirect_to @article else   render 'new'  end end  def edit   @article = article.find(params[:id]) end  def update  @article = article.find(params[:id])   if @article.update(article_params)    redirect_to @article  else    render 'edit'  end end   def show   @article = article.find(params[:id]) end  def destroy   @article = article.find(params[:id]) @article.destroy   redirect_to articles_path end 

in article model, article.rb, can set default_scope this:

default_scope -> { order('created_at desc') } 

however, method sort articles on pages. if only want sort them on 1 action, def index, might work better.

@articles = article.order('created_at desc') 

like @shamsulhaque said in comment.

here read default scopes.

update

if prefer use scopes, @rich says, syntax this:

scope :recent, ->(order = 'desc') { order(created_at: order.to_sym) } 

which have option, in controller, call either asc or desc so:

@articles = article.recent('asc') @articles = article.recent('desc') # although defaulted 'desc', need article.recent 

to explain bit, @rich included to_sym convert string 'desc' or 'asc' symbol :desc or :asc. if did not this, error like

direction should :asc or :desc 

hope helps.


Comments

Popular posts from this blog

javascript - RequestAnimationFrame not working when exiting fullscreen switching space on Safari -

Python ctypes access violation with const pointer arguments -