在Rails 5应用中,我遇到这样的情况:
<% report.periods.each do |period| %>
<ul>
<% period.assignments.where('assignments.end_date BETWEEN ? AND ?', period.start_date, period.end_date).order('start_date ASC').each_with_index do |assignment, index| %>
<li><%= index + 1 %></li>
<% end %>
</ul>
<% end %>
此代码的结果是每个数组都有其自己的索引。例如,如果您有两个句点(一个带有3个对象,另一个带有4个对象),则会得到以下内容:
<ul>
<li>1</li>
<li>2</li>
<li>3</li>
</ul>
<ul>
<li>1</li>
<li>2</li>
<li>3</li>
<li>4</li>
</ul>
我需要的结果是一个索引列表,而不是两个。使用上面的示例,我想要这样:
<ul>
<li>1</li>
<li>2</li>
<li>3</li>
<li>4</li>
<li>5</li>
<li>6</li>
<li>7</li>
</ul>
如何获得此结果?
更新:
这是报告模型:
class Report < ApplicationRecord
has_many :periods, dependent: :destroy
has_many :assignments, through: :periods
end
这是期间模型:
class Period < ApplicationRecord
belongs_to :report
has_many :assignments, through: :programs
end
这是分配模型:
class Assignment < ApplicationRecord
belongs_to :assignment_type
belongs_to :value_chain_activity
belongs_to :project_type
belongs_to :user
belongs_to :program
has_and_belongs_to_many :organizations, dependent: :destroy
has_many :activities, dependent: :destroy
has_many :cost_shares, dependent: :destroy
has_many :recommendations, dependent: :destroy
has_many :progress_reports, through: :recommendations
end
答案 0 :(得分:1)
您可以通过单个查询获得归类。我不确定,但是这段代码应该可以工作。
<% assignments= Assignment.joins(:period)
.where(periods: { id: report.period_ids })
.where('assignments.end_date BETWEEN periods.start_date AND periods.end_date')
.order('start_date ASC') %>
<ul>
<% assignments.each_with_index do |assignment, index| %>
<li><%= index + 1 %></li>
<% end %>
</ul>
答案 1 :(得分:0)
又快又脏:只需将<ul>
放在循环之外。就索引而言:获取值数组并消除重复项:
<% index_values = [] %>
<% report.periods.each do |period| %>
<% period.assignments.where('assignments.end_date BETWEEN ? AND ?', period.start_date, period.end_date).order('start_date ASC').each_with_index do |assignment, index| %>
<%= index_values << (index + 1) %>
<% end %>
<% end %>
<ul>
<% index_values.uniq.each do |index_value| %>
<li>
<%= index_value %>
</li>
<% end %>
</ul>