daniel langer
daniel langer

Reputation: 1975

Rails Controller Query

I am trying to display a list of users on a page based on an attribute of the current user. If the current user has its instance variable called :position as "High School" list all the users with the :position "College" (and vice versa). I know I do this in the controller with an if else statement, but I cant figure out what the query call should be. Right now I have:

if current_user.position= "High School"
  @user = User.all
else
  @user= User.all

As a template. However, I need to switch the @user= statements, but I cant figure out how to restrict it. Any help? Thanks!

<% @quizzes.each do |quiz| %>
  <tr>
    <td><h6><%= quiz.userName%></h6></td>
    <td><h6><%= quiz.q1 %></h6></td>
    <td><% for q in quiz.q2 %>
      <% if q != nil %>
        <h6><%= q  %></h6>
      <% end %>
    <% end %>
    <td><h6><%= quiz.q3 %></h6></td>
    <td>X</td>
  </tr>

Upvotes: 0

Views: 1232

Answers (3)

Mark Paine
Mark Paine

Reputation: 1894

Perhaps this is what you're looking for?

if current_user.position == "High School"
   @users = User.where(:position => "College")
else
   @users = User.where(:position => "High School")
end

Upvotes: 1

Erik Petersen
Erik Petersen

Reputation: 2357

Rails 3:

if current_user.position == "High School"
   @user = User.where(:position => "College")
else
   @user = User.where(:position => "High School")
end

Rails 2:

if current_user.position == "High School"
  @user = User.find_all_by_position("College")
else
  @user = User.find_all_by_position("High School")
end

Upvotes: 2

kevinhyunilkim
kevinhyunilkim

Reputation: 864

One possible solution is to use scope in model class.

Define scopes in User model

class User < ActiveRecord::Base
  ...

  scope :college,    where(position: 'College')
  scope :highschool, where(position: 'High School')
end

and in your controller,

if current_user.position == "High School"
  @users = User.college
else
  @users = User.highschool
end

Hope it would be help.

Upvotes: 2

Related Questions