Home > Mobile >  Ruby on Rails - Show only rows with certain conditions
Ruby on Rails - Show only rows with certain conditions

Time:01-04

I am a newbee on RoR and wants to know how to select rows from a database. In this case i want to have rows of all players that plays rugby.

<% @players.select(:sport).find ("Rugby") do |rugby| %>
  <%= rugby %>
<% end %>

CodePudding user response:

I would do this kind of thing in a controller and pass the information to your view layer.

Controller:

# We can use a `where` to select all players that have a sport of "Rugby"
@players = Player.where('sport = ?', 'Rugby')

View:

<% @players.each do |p| %>
  <%= p %>
<% end %>

CodePudding user response:

You can add a scope to your Player model like this:

class Player < ApplicationRecord
  scope :rugby, -> { where(sport: "Rugby") }
end

and you can use it in your controller to get the Rugby players like this:

@players = Player.rugby

and in your form:

<% @players do |player| %>
  <%= player %>
<% end %>
  •  Tags:  
  • Related