I'd like to use something like
scope :published, -> { where(:published => true) }
on my Article model only if the user is not signed in. If the user is signed in then I'd like to show all articles. I realize that the Article model itself does not have access to Devise's user_signed_in?
method so this logic should probably live in the controller.
The problem is that in the controller it would cause a lot of redundancy, as such:
def index
if params[:search].present?
@search = params[:search]
if user_signed_in?
@articles = Article.where('title LIKE ? OR body LIKE ?', "%#{@search}%", "%#{@search}%")
else
@articles = Article.published.where('title LIKE ? OR body LIKE ?', "%#{@search}%", "%#{@search}%")
end
elsif params[:uid].present?
@user = User.find(params[:uid])
if user_signed_in?
@articles = @user.articles.order :created_at
else
@articles = @user.articles.published.order :created_at
end
else
if user_signed_in?
@articles = Article.all.desc
else
@articles = Article.published.desc
end
end
end
Is there a better way I can avoid redundancy here but always check if the user is signed in before using the published
scope?
Thanks