Reputation: 694
Hi i have a controller in rails where i call all my players in database.
@candidates = Player.order("created_at DESC")
What i need is to show just the ones that have "active=1" un the database.. how can i add the where clause on this..
Tried this.. THE PROBLEM is that active is a table call "users" and im fetching "players" table..
@candidates = Player.where("active = ?", "1").order("created_at DESC")
Im lost :(
This is part of the player model
class Player < ActiveRecord::Base
belongs_to :user
Candidate model
class Candidate < ActiveRecord::Base
attr_accessible :country_id
end
Candidates controller
class CandidatesController < SecureController
skip_authorize_resource :only => [:index, :show]
# GET /players
# GET /players.json
def index
@candidates = Player.order("created_at DESC")
position = params[:position]
minyear = params[:minyear]
maxyear = params[:maxyear]
citizen = params[:nation]
@candidates = Player.scoped # for Rails 3
if params[:position].present?
@candidates = @candidates.where(position: position)
end
if params[:minyear].present?
@candidates = @candidates.where("birthday >= ?", minyear)
end
if params[:maxyear].present?
@candidates = @candidates.where("birthday <= ?", maxyear)
end
if params[:minyear].present? && params[:maxyear].present?
@candidates = @candidates.where("birthday >= ? AND birthday <= ?", minyear, maxyear)
end
respond_to do |format|
format.html # index.html.erb
format.json { render json: @candidates }
end
authorize! :show, :candidates
end
Upvotes: 0
Views: 1405
Reputation: 12826
You need to join the users table:
Player.joins(:user).where("users.active = ?", "1").order("players.created_at DESC")
Also a better way to write the condition is:
Player.joins(:user).where(users: { active: true }).order("players.created_at DESC")
Upvotes: 3