Rails3:如何将默认条件设置为has_many
我有盒子和球。球在盒子里。球可以是红色和绿色。
class Box < ActiveRecord::Base
has_many :balls
end
class Ball < ActiveRecord::Base
belongs_to :box
scope :green, where(:color => "green")
end
我只想用绿球设置 has_many 。我知道 finder_sql 方法存在,但我不知道如何通过范围进行设置。
我希望以下示例是等效的:
@orders = @box.balls
@orders = @box.balls.green
I have boxes and balls. Balls are in boxes. Ball can be either red and green.
class Box < ActiveRecord::Base
has_many :balls
end
class Ball < ActiveRecord::Base
belongs_to :box
scope :green, where(:color => "green")
end
I want to set has_many only with green balls. I know that finder_sql method exists, but i don't know how to set via scopes.
I want that following examples to be equivalent:
@orders = @box.balls
@orders = @box.balls.green
如果你对这篇内容有疑问,欢迎到本站社区发帖提问 参与讨论,获取更多帮助,或者扫码二维码加入 Web 技术交流群。
绑定邮箱获取回复消息
由于您还没有绑定你的真实邮箱,如果其他用户或者作者回复了您的评论,将不能在第一时间通知您!
发布评论
评论(4)
您始终可以使用:
它适用于 Rails3,但我不确定此语法是否会因某些 ActiveRecord::Relation 等效项而被弃用。在 Rails3 相关的官方文档中,这个语法仍然可用,所以我想这会像 2.3.x 分支中一样保留下来。
You can always use:
It works in Rails3, but I am not sure if this syntax won't be deprecated due to some ActiveRecord::Relation equivalent. In the official documentation relased with Rails3 this syntax is still available, so I guess this stays out like it was in 2.3.x branch.
在 Rails 3 中,它略有变化:
信用和更多信息< /a>
And in Rails 3, it's changed slightly:
Credit and more information
这是一个老问题,但我只是想做同样的事情,并且在搜索时遇到了这个问题。我从未找到解决方案,但我想出了一些效果很好的方法。
对于您的示例,您可以这样做:
我不知道这样做的含义,但经过一些初步测试后,它似乎可以正常工作。还可以设置其他值,例如
eager_load_values
、join_values
、order_values
等。This is an old question, but I was just looking to do the same thing, and I came across this question while searching. I never found a solution, but I came up with something that works well.
For your example, you can do this:
I'm not aware of the implications of doing this, but after some initial testing, it appears to work without issue. There are other values that can be set, like
eager_load_values
,join_values
,order_values
, etc.用这个
Use this