在show view中排序结果

时间:2014-02-09 16:27:20

标签: ruby-on-rails

我有两个模型 - service_request_work_plan,其中service_request_work_plan has_many work_plan_tasks,work_plan_tasks属于service_request_work_plan。链接工作,关联正确呈现,我在show_reqeust_work_plan的show视图中有下面的代码,其目标是按顺序显示work_plan_tasks。 show动作正常,但它们没有按顺序显示(即order_of_exeuction)。我错过了什么?

<table>
  <tr>
    <th>Order of Execution</th>
    <th>Task</th>
    <th>SLO</th>
    <th>Task Instructions</th>
  </tr>
  <% @service_request_work_plan.work_plan_tasks.each do |work_plan_task| %>
    <tr>
      <td><%= work_plan_task.order_of_execution %></td>
      <td><%= work_plan_task.task_name %></td>
      <td><%= work_plan_task.task_slo %></td>
      <td><%= work_plan_task.task_instructions %></td>
    </tr>
  <% end %>
</table>

class ServiceRequestWorkPlan < ActiveRecord::Base
  attr_accessible :testing_company_id, :work_plan_name, :work_plan_comments
  belongs_to :testing_company
  has_many :work_plan_tasks
end

class WorkPlanTask < ActiveRecord::Base
  attr_accessible :testing_company_id, :task_name, :task_instructions, :service_request_work_plan_id, :task_slo, :order_of_execution
  belongs_to :testing_company
  belongs_to :service_request_work_plan

end

  def show
    @service_request_work_plan = ServiceRequestWorkPlan.find(params[:id])
  end

2 个答案:

答案 0 :(得分:0)

从控制器查询数据库时,为.order(order_of_execution: :asc)添加work_plan_tasks。见http://guides.rubyonrails.org/active_record_querying.html#ordering

控制器:

def show
  @service_request_work_plan = ServiceRequestWorkPlan.find(params[:id]).work_plan_tasks.order(order_of_execution: :asc)
end

答案 1 :(得分:0)

更改此行:

<% @service_request_work_plan.work_plan_tasks.each do |work_plan_task| %>

进入这一行:

<% @service_request_work_plan.work_plan_tasks.all.order(:order_of_execution).each do |work_plan_task| %>

默认顺序为升序,因此上述行已完成。如果您需要降序:

order(:order_of_execution => :desc)