Tag: 默认范围

default_scope在某些情况下会中断(更新|删除|销毁)_all

我相信这是Rails 3中的一个错误。我希望有人能指引我朝着正确的方向前进。 下面发布的代码纯粹是为了说明这个问题。 希望这不会混淆问题。 鉴于我有一个Post模型和一个Comment模型。 发表has_many评论,评论发表于发帖。 在Post模型上设置default_scope,定义join()和where()关系。 在这种情况下,()依赖于连接()。 通常post不依赖于评论。 再说一遍,我只想举一个简单的例子。 当where()依赖于join()时,这可能是任何情况。 class Post :destroy default_scope joins(:comments).where(“comments.id < 999") end class Comment true end 运行以下命令: Post.update_all(:title => Time.now) 生成以下查询,并最终抛出ActiveRecord :: StatementInvalid: UPDATE `posts` SET `title` = ‘2010-10-15 15:59:27’ WHERE (comments.id < 999) 同样,update_all,delete_all,destroy_all的行为方式相同。 当我的应用程序在尝试更新counter_cache时抱怨时,我发现了这种行为。 最终深入研究update_all。

Rails 3上的所有者过滤的模型对象

我需要对我的ActiveRecord模型进行一些过滤,我想通过owner_id过滤我的所有模型对象。 我需要的东西基本上是ActiveRecord的default_scope。 但我需要通过会话变量进行过滤,该变量无法从模型中访问。 我已经阅读了一些解决方案 ,但没有一个可行,基本上任何一个都说你可以在声明default_scope时使用session。 这是我对范围的声明: class MyModel session[:user_id]) } … end 简单吧? 但它没有说方法会话不存在 。 希望你能帮忙

rails3 default_scope,以及迁移中的默认列值

class CreateCrews false t.timestamps end end def self.down drop_table :crews end end class Crew :crew_users belongs_to :user default_scope where(:approved => true) end 当我进入控制台并创建新记录时,“已批准”属性设置为true,为什么? 如何将其自动设置为默认值(false),如我的迁移文件中所示? wojciech@vostro:~/work/ze$ rails console Loading development environment (Rails 3.0.0) ruby-1.9.2-p0 > c = Crew.new => #

在Rails中覆盖default_scope

在我的Post.rb模型中,我有default_scope :conditions => {:deleted => ‘false’} 但是如果我尝试运行Post.find(:all, :conditions => “deleted=’false'”) ,它将不会返回任何内容。 就像default_scope优先于所有内容一样。 我想要它,以便当我执行Post.find()它不会返回已删除的post,但我也希望能够在需要时访问它们。 在我的查询或我的Rails模型中需要更改什么? 谢谢。

default_scope和association

假设我有一个Post模型和一个Comment模型。 使用常见模式,Post has_many Comments。 如果Comment设置了default_scope: default_scope where(“deleted_at IS NULL”) 无论范围如何,如何轻松检索post上的所有评论? 这会产生无效结果: Post.first.comments.unscoped 这会生成以下查询: SELECT * FROM posts LIMIT 1; SELECT * FROM comments; 代替: SELECT * FROM posts LIMIT 1; SELECT * FROM comments WHERE post_id = 1; 运行: Post.first.comments 生产: SELECT * FROM posts LIMIT 1; SELECT * FROM comments WHERE deleted_at IS NULL […]

Rails 4 – acts_as_votable,更改默认排序顺序

我有一个Rails应用程序,允许在某些模型上投票。 在我的一个模型中,我想更改default_scope以便首先显示投票最多的对象。 我在我的模型文件中尝试了以下内容: def self.default_scope order(‘votes_for.size DESC’) end 这给了我以下错误: SQLite3::SQLException: no such column: votes_for.size: SELECT “solutions”.* FROM “solutions” WHERE “solutions”.”competition_id” = ? ORDER BY votes_for.size DESC 我想知道是否有一种方法可以更改默认的默认排序顺序,我正在做的事情显然不起作用。 如果可能的话,使它在控制器级别(非默认顺序)工作的解决方案也会很好。

我如何对我的默认范围进行rspec测试

我的模型有default_scope(:order =>’created_at’)我的测试(rspec,factory girl,shoulda等)是: require ‘spec/spec_helper.rb’ describe CatMembership do context “is valid” do subject { Factory.build(:cat_membership) } it { should be_valid } it { should belong_to :cat} it { should belong_to :cat_group} it { should have_db_column(:start_date)} it { should have_db_column(:end_date)} end end