0

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>
1
  • What version of rails are you using? Commented May 3, 2012 at 0:27

3 Answers 3

2

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
Sign up to request clarification or add additional context in comments.

Comments

2

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.

2 Comments

If you added the scopes, and want to remove the if statement, you could do: @users = User.send current_user.position
Okay I realized that I am actually laying out my view like an idiot so maybe you can help me one more time. My view lays out a table of quizzes.each and a quiz belongs to a user. So by updating user, it has no affect on the quizzes that are being displayed. How can I modify the @quizzes variable in the user controller so it only finds quizzes that belongs to users of the opposite varialbe? I'll add the table to my code.
1

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

Comments

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.