簡體   English   中英

從Ruby on Rails中的表中調用特定對象

[英]Calling specific object from a table in Ruby on Rails

現在,我試圖在所有用戶如何在該特定測驗中得分的測驗末尾顯示記分板。 為此,我正在調用索引並顯示用戶名,類別和分數:

 <% @participations.each_with_index do |participation, index| %>
    <tr>
      <td>#<%= index + 1 %></td>
      <td><%= participation.user.username %></td>
      <td><%= participation.category %></td>
      <td><%= participation.score %></td>
    </tr>
  <% end %>

通過調用索引,它將顯示參與模型中的所有分數。 例如,如果我有三個測驗類別:歷史,體育和商業,它將在此表中顯示所有這三個類別的分數。

要解決此問題,我相信我需要調用一個特定的對象(在本例中為“歷史”類別列),以過濾記分板表中該測驗的分數。 通過更改索引查詢是否有可能?

注意:遷移后的“參與表”如下所示:

  class CreateParticipations < ActiveRecord::Migration
    def change
      create_table :participations do |t|
        t.references :user
        t.string :category
        t.boolean :finished, default: false
        t.integer :current_question_index, default: 0
        t.integer :score, default: 0
        t.timestamps
    end
  end
end 

記分板控制器:

 class ScoreboardController < ApplicationController
   def index
     @participations = Participation.where(finished: true).order(score: :desc)
       end
   end

簡單的答案是,您要調用participations表的所有值。 您需要過濾查詢以僅返回所需的category值:

 @participations = Participation.where(finished: true, category: "history").order(score: :desc)

一個很好的方法是使用以下方法:

#config/routes.rb
resources :scoreboards do
   get ":category", to: :index, on: :collection #-> url.com/scoreboards/history
end

這將允許您使用:

#app/controllers/scoreboards_controller.rb
class ScoreboardsController < ApplicationController
   def index
       if params[:category]
         @participations = Participation.where(finished: true, category: params[:category]).order(score: :desc)
       else
         @participations = Participation.where(finished: true).order(score: :desc)
       end
   end
end

這里的一個提示是將enum用於您的categories

#app/models/participation.rb
class Participation < ActiveRecord::Base
   enum category: [:history, :sports, :business]
end

您必須將表格更改為category整數

change_column :participations, :category, :integer, default: 0

enum將為您定義的每個類別存儲整數 如果您閱讀文檔,將會看到其有效性的程度(允許您加載各種實例方法等)。

最重要的是,它將使您的數據庫變干-使您可以存儲各種類別的數字,從而使程序更高效,並最終使您可以更均勻地擴展它。

     class ScoreboardController < ApplicationController
       def index
         if params[:category].present?
           @participations = Participation.where(finished: true, params[:category]).order(score: :desc)
         else
           @participations = Participation.where(finished: true).order(score: :desc)
         end
       end
     end

然后在url中可以有類似index?category = history的過濾器

暫無
暫無

聲明:本站的技術帖子網頁,遵循CC BY-SA 4.0協議,如果您需要轉載,請注明本站網址或者原文地址。任何問題請咨詢:yoyou2525@163.com.

 
粵ICP備18138465號  © 2020-2024 STACKOOM.COM