有没有更多的红宝石方式来做这个逻辑

时间:2011-02-08 16:22:05

标签: ruby-on-rails ruby ruby-on-rails-3

这是我的控制器索引操作

sub1 = "(select sum(courses_users.know) from courses_users where courses_users.course_id = courses.id) know_score"
sub2 = "(select levels.name from levels where levels.id = courses.level_id) level_name"
@courses = ActiveRecord::Base.connection.execute "select name,#{sub1},#{sub2} from courses order by level_id, know_score"
@total_score = User.count() * 2;

这是视图逻辑

<% level_name = "" %>
<% @courses.each do |course| %>
<% if course[2] != level_name %>
  <tr>
      <th colspan='2' style='text-align:left;'><br /><br /><%= course[2] %><br /><br /></th>
  </tr>
  <tr>
    <th>Title</th>
    <th>Knowledge Score</th>
  </tr>
  <% level_name = course[2] %>
<% end %>
<tr>
  <td><%= course[0] %></td>
  <td><%= (course[1].nil? ? 0 : course[1].to_i) %>/<%= @total_score %></td>
</tr>
<% end %>

这是循环中每个镜头的样子

["PHP - The Basics", #<BigDecimal:1033708d0,'0.31E2',9(18)>, "Beginner"]----------------

这看起来像是一个黑客,我很想让这更像红宝石

这是我的数据库结构,如果这将有帮助

create_table "courses", :force => true do |t|
  t.string   "name"
  t.integer  "target_id"
  t.integer  "level_id"
  t.datetime "created_at"
  t.datetime "updated_at"
  t.integer  "order_num"
end

create_table "levels", :force => true do |t|
  t.string   "name"
  t.datetime "created_at"
  t.datetime "updated_at"
end

1 个答案:

答案 0 :(得分:2)

我要做的第一件事是添加两个范围以从课程表中获取相关计数:

class Course
  has_many :courses_users
  belongs_to :level

  scope :with_know_score, joins(:courses_users).group("courses.id").select(["courses.*"," sum(courses_users.know) as know_score"])
  scope :with_level_name, joins(:level).select(["courses.*","levels.name as level_name"])
end

然后,您可以简化控制器代码:

@courses = Course.with_know_score.with_level_name
@total_score = User.count * 2

您的观看代码:

<% level_name = "" %>
<% @courses.each do |course| %>
  <% if course.level_name != level_name %>
    ...
    <% level_name = course.level_name %>
  <% end %>
  <tr>
    <td><%= course.name %></td>
    <td>
      <%= course.know_score || 0 %>/<%= @total_score %>
    </td>
  </tr>
<% end %>

在控制台中,您应该可以输入:

c = Course.with_know_score.with_level_name.first
c.name # 'PHP ...'
c.level_name # 'Beginner'
c.know_score #