Warning: file_get_contents(/data/phpspider/zhask/data//catemap/5/ruby-on-rails-4/2.json): failed to open stream: No such file or directory in /data/phpspider/zhask/libs/function.php on line 167

Warning: Invalid argument supplied for foreach() in /data/phpspider/zhask/libs/tag.function.php on line 1116

Notice: Undefined index: in /data/phpspider/zhask/libs/function.php on line 180

Warning: array_chunk() expects parameter 1 to be array, null given in /data/phpspider/zhask/libs/function.php on line 181
Ruby on rails Rails 4 ActiveRecord附加条件(多个.where)_Ruby On Rails_Ruby On Rails 4_Activerecord_Rails Activerecord - Fatal编程技术网

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)

是否运行两个单独的查询?不,它只是创建了一个关系。是否运行了两个单独的查询?不,它只是创建了一个关系。