Reputation: 1098
I want to to display all distinct records in a view. I have the following in my accounts_controler.rb file @account = Account.count("created_at", :distinct => true)
or should I use Account.distinct.count('date')
? If I read correctly rails 4 :distinct => true
is now deprecated
I'm not sure if that is correct. Here is the entire controller file:
class AccountsController < ApplicationController
before_action :authenticate_user!
before_action :set_account, only: [:show, :edit, :update, :destroy]
respond_to :html
def search
if params[:search].present?
@account = Account.search(params[:search])
else
@account = Account.all
end
end
def index
@account = Account.all.order("created_at DESC").page(params[:page]).per(10)
@account = Account.count("created_at", :distinct => true)
end
end
def show
@notes = Note.where(account_id: @account.id) #Where a note belong to the current account
end
def new
@account = Account.new
respond_with(@account)
end
def edit
end
def create
@account = Account.new(account_params)
@account.save
respond_with(@account)
end
def update
@account.update(account_params)
respond_with(@account)
end
def destroy
@account.destroy
respond_with(@account)
end
private
def set_account
@account = Account.find(params[:id])
end
def account_params
params.require(:account).permit(:first_name, :last_name, :return_client, :program_id, :insurance_id, :address, :phone)
end
I beleive there should be a ruby tag include in the index.html.erb file but I'm not sure of the syntax.
Upvotes: 1
Views: 398
Reputation: 4164
You can use the uniq
keyword to return all distinct records as follow:
def index
@accounts = Account.uniq.order("created_at DESC").page(params[:page]).per(10)
@accounts_count = Account.uniq.count
end
and then you will have access to the instance variable @accounts
in your index.html.erb
file.
Upvotes: 2
Reputation: 1545
You are right.
Rails 3:
Account.count(:created_at, distinct: true)
Rails 4:
Account.distinct.count('date')
Upvotes: 3