select_collection on Ruby on Rails

Asked

Viewed 349 times

1

If I want to return the options of Active and Inactive so that I select, I use the following code in the view, then it returns the 2 status:

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

but I need to return not the 2 status, but only Active or Inactive, depending on how it is in the bank, how I could do ?

  • Your question is not very clear. It is more clearly exemplified what is happening and how you want it to look. Using examples becomes clearer.

  • Ah you’re the guy who and does not mark answers as certain review your previous questions dude. Mark these answers as accepts help who answered and who is seeking the solution as you.

  • 1

    Oh yeah. Sorry. I’ll go over my questions again...

  • Edit your answer so we can help here too!

  • I managed to solve, I will post below the solution

2 answers

2

Create a Scope on 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 ] }) %>

1


I was able to solve it this way...

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

On my controller

def index
   #@students = Student.all
  #render :json => @students
  student = Student.new
  @students = student.ajustaDadosAluno
end
  • Are you using this SQL by necessity or because you were unable to play it using the Rails ORM? I believe you can turn this method into a Scope.

  • opa... Obg by the comment then I could not reduce to ORM, I get lost in the joins, as it would turn into a Scope ?

Browser other questions tagged

You are not signed in. Login or sign up in order to post.