假设我有以下课程
class SolarSystem < ActiveRecord::Base
has_many :planets
end
class Planet < ActiveRecord::Base
scope :life_supporting, where('distance_from_sun > ?', 5).order('diameter ASC')
end
Run Code Online (Sandbox Code Playgroud)
Planet有范围life_supporting和SolarSystem has_many :planets.我想定义我的has_many关系,这样当我询问solar_system所有关联时planets,life_supporting范围会自动应用.基本上,我想solar_system.planets == solar_system.planets.life_supporting.
我不希望改变scope :life_supporting在Planet以
default_scope where('distance_from_sun > ?', 5).order('diameter ASC')
我还想通过不必添加来防止重复 SolarSystem
has_many :planets, :conditions => ['distance_from_sun > ?', 5], :order => 'diameter ASC'
我想要有类似的东西
has_many :planets, :with_scope => :life_supporting
正如@phoet所说,使用ActiveRecord可能无法实现默认范围.但是,我发现了两个潜在的工作.两者都可以防止重复.第一个是长期保持明显的可读性和透明度,第二个是助手类型方法,其输出是显式的.
class SolarSystem < ActiveRecord::Base …Run Code Online (Sandbox Code Playgroud) 我正在从模型中提取类别列表.在管理部分,我想用它来为产品分配类别.它工作正常,但列表按顺序显示已添加类别.我想按字母顺序对它们进行排序,但我无法将其排除在外.
我相信这很简单(希望如此)
这是我的代码:
<%= simple_form_for(@game) do |f| %>
<%= f.input :name %>
<%= f.input :description %>
<%= f.input :copy %>
<%= f.input :image %>
<%= f.input :thumbnail %>
<%= f.input :heroimage %>
<%= f.association :category, collection: @categories %>
<%= f.button :submit %>
<% end %>
Run Code Online (Sandbox Code Playgroud)
我试图添加一个.sort_by(desc)或只是.sort在收集方法,但它不会更改列表.
干杯