Home > Software engineering >  Show only the last evaluation of every category in Ruby on rails
Show only the last evaluation of every category in Ruby on rails

Time:06-09

I have many Sectors and every sector has many Evaluations (it´s just an integer of how clean is the sector), I Need to show the name of the sector and only the last Evaluation of every Sector

With this code, I have all the evaluations but I only need the last of every sector

<% @evaluations.each do |evaluation| %>
  <%= evaluation.sector.name %>
  <%= evaluation.note %>
<% end %>
create_table "sectors", force: :cascade do |t|
    t.string "name"
    t.datetime "created_at", precision: 6, null: false
    t.datetime "updated_at", precision: 6, null: false
 end

create_table "evaluations", force: :cascade do |t|
    t.bigint "sector_id", null: false
    t.integer "note"
    t.datetime "created_at", precision: 6, null: false
    t.datetime "updated_at", precision: 6, null: false
    t.index ["sector_id"], name: "index_evaluacions_on_sector_id"
end

class Evaluation < ApplicationRecord
  belongs_to :sector
end
class Sector < ApplicationRecord
end

Thanks in advance

CodePudding user response:

Have a missing has_many :evaluations in sectors.rb and then

<% @sectors.each do |sector| %>
<%= sector.name %>
<%= sector.evaluations.last.note %>
<% end %>

CodePudding user response:

You can add has_one association to the Sector model

class Sector < ApplicationRecord
  has_one :last_evaluation, -> { order(created_at: :desc) }, class_name: 'Evaluation'
end

And then in your view:

<% @sectors.each do |sector| %>
  <%= sector.last_evaluation.note %>
<% end %>
  • Related