In my application I have user and activities tables and the user has three activities.
I have a home page with three buttons on it. If the user presses button 1, I want to navigate to the activities index page and set the attribute activity_type
to = 1
. If the user presses button 2, I want to navigate to the activities index page and set the activity_type
to 2
, etc.
Right now I have:
<%= link_to 'Personal Activity', user_activities_path(:user_id => current_user.id, :activity_type => 1) %>
<%= link_to 'Physical Activity', user_activities_path(:user_id => current_user.id, :activity_type => 2) %>
<%= link_to 'Community Activity', user_activities_path(:user_id => current_user.id, :activity_type => 3) %>
In my activities controller index
method I have:
class ActivitiesController < ApplicationController
def index
@activities = Activity.all
@activity_type = params[:activity_type]
case @activity_type
when 1
$activity_type_var = 1
when 2
$activity_type_var = 2
else
$activity_type_var = 3
end
end
I have this in my activities/index.html.erb:
<% if $activity_type_var == 1 %>
<%= "Personal Activity" %>
<% elsif $activity_type_var == 2 %>
<%= "Physical Activity" %>
<% elsif $activity_type_var == 3 %>
<%= "Community Activity" %>
<% else %>
<%= "NOT WORKING" %>
<% end %>
No matter what link I choose from the home page, "Community Activity" shows on the view, meaning the activity_type
always seems to be 3. I don't think it is recognizing the activity_type
I am passing through the link in the home page.
Is there a different way to do this, or am I doing this incorrectly?
You are passing an integer in your link (
:activity_type => 1
), but everything is sent as a string into Rails. Soparams[:activity_type]
is a string, not an integer (ie. "1" not 1). So when you do yourcase
statement you are trying to compare "1" to 1, 2, orelse
. And since"1" != 1
" (or 2) your case is always going to use the default case and set$activity_type_var
to 3.Don't use global variables. An instance variable would be just fine.