vendredi 21 avril 2017

Rails: Allow one session to be :pinned at a time

I'm working on pinning a session for a company to the top of a list.

A company should be able to pin a single spark session to the top of their list. Because a company can only have a single pinned session, if they try to pin a new session it should save the newly pinned session and unpin any other session automatically.

Model:

class SparkSession < ActiveRecord::Base
  def pinned!
    self.pinned = true
    self.save!
  end
end

Controller:

class SparkSessionsController < SubdomainsController
  def index
    @spark_sessions = @company.spark_sessions.where(is_archived: false).order_by_pinned_then_created
  end
  def pin
    load_spark_session
    @spark_session.pinned!
    flash[:notice] = 'Spark Session pinned'
    redirect_to action: :index
  rescue ActiveRecord::RecordInvalid
    flash.now[:error] = 'Failed to pin Spark Session'
    redirect_to action: :index
  end
end

View:

%td= link_to 'Pin', pin_spark_session_path(tbl), method: :post

What is the most efficient way to handle the repinning of sessions for the company? Moreover, is there a way in the view or method more distinctive a pinned post with a styling element?

Aucun commentaire:

Enregistrer un commentaire