select_collection in Ruby on rails

1
If I want to return the Active and Inactive options for me to select, I use the following code in the view, so it returns the 2 statuses:

>
<%= select(:student, :status, Situation.all.collect { |c| [ c.descricao, c.id ] }) %>

But I need to return not the 2 statuses, but only Active or Idle , depending on how you are in the database, how could I do?

    
asked by anonymous 14.09.2016 / 15:43

2 answers

1

I was able to solve it as follows ...

In my view

<% @students.each do |student| %>
  <tr>
  <td><%= student['nome'] %></td>
    <td><%= student['matricula'] %></td>
    <td><%= student['sala'] %></td>
    <td><%= student['status']%></td>

    <td><%= link_to 'Edit', edit_student_path(student['id']) %></td>
    <td><%= link_to 'Destroy', student_path(student['id']), method: :delete, data: { confirm: 'Are you sure?' } %></td>

  </tr>
<% end %>

In my Model

def ajustaDadosAluno
    queryRoom = "select s.id AS id,s.name AS nome, s.registration AS matricula, 
    r.description AS sala, si.descricao AS status FROM students s
    INNER JOIN rooms r ON r.id = s.room_id
    INNER JOIN situations si ON s.room_id = si.id"
    retorno= ActiveRecord::Base.connection.execute(queryRoom)
end

In my controller

def index
   #@students = Student.all
  #render :json => @students
  student = Student.new
  @students = student.ajustaDadosAluno
end
    
15.09.2016 / 20:44
2

Create a scope in the model:

class Situation < Application Record
    #suas validações e parametros

    scope :active, -> { where(status: 'active' }
    scope :inactive -> { where(status: 'inactive' }
end

So you can call in your view:

#pega somente os ativos
<%= select(:student, :status, Situation.active.collect { |c| [ c.descricao, c.id ] }) %>

#pegar somente os inativos
<%= select(:student, :status, Situation.inactive.collect { |c| [ c.descricao, c.id ] }) %>
    
22.09.2016 / 17:40