嗨我在轨道上有一个控制器,我可以在数据库中呼叫所有玩家。
@candidates = Player.order("created_at DESC")
我需要的是只展示那些拥有“active = 1”的数据库。我怎样才能在这个上添加where子句..
尝试过这个..问题是主动是一个表叫“用户”而我正在取“玩家”表..
@candidates = Player.where("active = ?", "1").order("created_at DESC")
我输了:(
这是播放器模型的一部分
class Player < ActiveRecord::Base
belongs_to :user
候选人模特
class Candidate < ActiveRecord::Base
attr_accessible :country_id
end
候选人控制员
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
答案 0 :(得分:3)
您需要加入用户表:
Player.joins(:user).where("users.active = ?", "1").order("players.created_at DESC")
编写条件的更好方法是:
Player.joins(:user).where(users: { active: true }).order("players.created_at DESC")