2016-06-10 55 views
2

從Rails開始,我想將ORM部分從視圖移動到模型。Rails 4:移動Active Record從視圖到模型生成的集合

怎麼辦?

實施例:

<%= f.collection_check_boxes :instructor_ids, Instructor.joins(:events).where(events: { :start_time => Date.today.beginning_of_week..Date.today.end_of_week }).group("instructor_id").having("count(instructor_id) < 4"), :id, :name do |ib| %> 
    <%= ib.label(class: "checkbox-inline input_checkbox") {ib.check_box(class: "checkbox") + ib.text } %> 
<% end %> 

感謝。

路易斯,

感謝您指出我的作用域。我解決這個如下。

app/views/events/_form.html.erb 

<%= f.collection_check_boxes :instructor_ids, Event.instructor_week_limit, :id, :name do |ib| %> 
    <%= ib.label(class: "checkbox-inline input_checkbox") {ib.check_box(class: "checkbox") + ib.text } %> 
<% end %> 

應用程序/模型/ event.rb

scope :instructors_this_week, -> { Instructor.joins(:events).where(events: { :start_time => Date.today.beginning_of_week..Date.today.end_of_week }) } 
    scope :instructor_week_limit, -> { instructors_this_week.group("instructor_id").having("count(instructor_id) < 4") } 
+0

嗯,這是一個很好的舉動,做到這一點。附:或者你有關於這個過程的任何實際問題? – potashin

回答

相關問題