Ruby on rails Rails 4 ActiveRecord附加条件(多个.where)
我想附加Ruby on rails Rails 4 ActiveRecord附加条件(多个.where),ruby-on-rails,ruby-on-rails-4,activerecord,rails-activerecord,Ruby On Rails,Ruby On Rails 4,Activerecord,Rails Activerecord,我想附加和条件取决于如下条件: @flag = true || false; @results = Model.where(conditions).where(conditions_depend_on_flag); //简单的方法是: if (@flag) { @results = Model.where(conditions); } else { @results = Model.where(conditions).where(conditions_depend_on_fl
和
条件取决于如下条件:
@flag = true || false;
@results = Model.where(conditions).where(conditions_depend_on_flag);
//简单的方法是:
if (@flag) {
@results = Model.where(conditions);
} else {
@results = Model.where(conditions).where(conditions_depend_on_flag);
}
我期望的示例:
@results = Model.where(conditions).where(conditions_depend_on_flag, @flag == true);
我不知道有没有可能
你能给我一些建议吗?我们可以将2个条件组合成1个where语句:
@results = Model.where(conditions)
@results = @results.where(conditions_depend_on_flag) if @flag
为了方便起见,我假设:
conditions = created_at < 1.day.ago
conditions_depend_on_flag = updated_at > 1.day.ago
conditions=创建时间<1.day.ago
条件取决于标志=更新时间>1.day.ago
因此,查询将是:
Model.where(
'created_at < ? AND (? OR updated_at > ?)', 1.day.ago, !@flag, 1.day.ago
)
Model.where(
“创建时间<和(?或更新时间>?)”,1.day.ago,!@flag,1.day.ago
)
漂亮的SQL:)我们可以将2个条件组合成1个where语句: 为了方便起见,我假设:
conditions = created_at < 1.day.ago
conditions_depend_on_flag = updated_at > 1.day.ago
conditions=创建时间<1.day.ago
条件取决于标志=更新时间>1.day.ago
因此,查询将是:
Model.where(
'created_at < ? AND (? OR updated_at > ?)', 1.day.ago, !@flag, 1.day.ago
)
Model.where(
“创建时间<和(?或更新时间>?)”,1.day.ago,!@flag,1.day.ago
)
漂亮的SQL:)为SQL条件使用作用域 模型中
scope :conditions_depend_on_flag, ->(flag) { where(....) if flag }
任何地方
@results = Model.where(conditions).conditions_depend_on_flag(@flag)
对sql条件使用作用域 模型中
scope :conditions_depend_on_flag, ->(flag) { where(....) if flag }
任何地方
@results = Model.where(conditions).conditions_depend_on_flag(@flag)
是否运行两个单独的查询?不,它只是创建了一个关系。是否运行了两个单独的查询?不,它只是创建了一个关系。