0

In Rails 3.1.12 view, we would like to iterate starting from 2nd record. Here is the code:

<%= f.fields_for :task_templates, @project_task_template.task_templates.offset(1).each do |builder| %> 
    <p><%= render('task_templates', :f => builder) %></p> 
<% end if @project_task_template.task_templates.size > 1 %> 

What we find out is that the first record is still showing in the view and offset(1) is not skipping the first record. What's the right way to iterate starting from 2nd record in Rails (without checking the order of the record)?

4

1 回答 1

4

The reason is the object @project_task_template.task_templates is an Array instead of Query object. You can't chain offset on the array.

It's possible to solve this at view but I recommend to put such logic in model scope

class ProjectTaskTemplates < ActiveRecords::Base
  default_scope offset(1)
  # or any other scope if you don't want to put it as default
end

Or put it in controller but not View. Your view should be dumb to use instance from controller directly.

class ProjectTaskTemplates < ActiveRecords::Base
  scope :offset_by_1, offset(1) 
end

# Controller
@project_task_templates = Product.other_queries.offset_by_1
于 2013-06-10T11:01:03.663 回答