我会回答我如何解决这个使用范围,因为其他用户已经要求这个。与继续上面的例子,假设我们有发票和员工型号:
class Invoice < ActiveRecord::Base
belongs_to :employee
end
class Employee < ActiveRecord::Base
has_many :invoices
# the select_menu scope takes an employee instance as an argument
# and adds this employee to the list of 'active' employees
scope :active, where(active: true)
scope :select_menu, lambda { |another_employee| active << another_employee }
end
然后,在你看来/表单,使用select_menu范围,并通过在当前(无效)员工将它们添加到掇下拉列表:
/views/invoices/_form.html.erb
<%= simple_form_for @invoice do |f| %>
<%= f.association :employee, collection: Employee.select_menu(@invoice.employee).sort_by(&:name), label_method: :first_last, include_blank: "" %>
...
<% end %>
因此,假设这种形式在新的正常使用和编辑的观点 - 当新的动作被调用,没有链接的员工,只有在职职工都在滴出下。编辑操作被调用时,@invoice有一个(可能不活动的)员工,并且该员工将使用该范围添加到活动员工列表中。
如果有人对如何做到这一点有了更好的想法,我全都听过,但这是迄今为止我发现的最干净的解决方案。
我已经想出了如何通过在窗体的“编辑”操作中手动添加非活动员工来完成此操作。这种方法的问题是,我需要为每个表单上的每个选择框执行此操作,而这只是很多代码。我希望有更优雅的方式! – FireDragon
也想出了一个半肮脏的方式来做到这一点在模型中使用示波器,这在我看来更好,但我仍然不喜欢它... – FireDragon
随意分享解决方案 – MZaragoza