issue with if-else in a view - ruby-on-rails

I am following the railstutorial and now got into the point where header will change dynamically depending on whether the user is logged in or not, using a conditional dropdown as shown below
<header class="navbar navbar-fixed-top navbar-inverse">
<div class="container">
<%= link_to "sample app", root_path, id: "logo" %>
<nav>
<ul class="nav navbar-nav navbar-right">
<li><%= link_to "Home", root_path %></li>
<li><%= link_to "Help", help_path %></li>
<% if logged_in? %>
<li><%= link_to "Users", '#' %></li>
<li class="dropdown">
<a href="#" class="dropdown-toggle" data-toggle="dropdown">
Account <b class="caret"></b>
</a>
<ul class="dropdown-menu">
<li><%= link_to "Profile", current_user %></li>
<li><%= link_to "Settings", '#' %></li>
<li class="divider"></li>
<li>
<%= link_to "Log out", logout_path, method: "delete" %>
</li>
</ul>
</li>
<% else %>
<li><%= link_to "Log in", login_path %></li>
<% end %>
</ul>
</nav>
And here is the logged_in? method defined in the helper
module SessionsHelper
# Logs in the given user.
def log_in(user)
session[:user_id] = user.id
end
# Returns the current logged-in user (if any).
def current_user
#current_user ||= User.find_by(id: session[:user_id])
end
# Returns true if the user is logged in, false otherwise.
def logged_in?
!current_user.nil?
end
end
For some reason this is not working, although I have copied the tutorial exactly. I am not sure if the line (if_logged_in?) is not being called or it is called but returns false. The else block gets executed by the way
I was wondering if there is anyway I can check if the method defined in the helper (logged_in?) is working and gets called correctly? Something like printing an output from the method itself?

A quick way to check whether that method's being called, and what's happening in it, is to throw a debug statement in there, like so:
def logged_in?
Rails.logger.debug("\n\n *** logged_in? #{current_user}")
!current_user.nil?
end
You load the page and then look at your development log and see if that line is there, and whether the user exists.
For more details about debugging, see http://guides.rubyonrails.org/debugging_rails_applications.html.
Hope that helps.

Related

How do I DRY up my active nav links?

I am looking to pass this into the controller so I don't have to repeat or ask for path names.
<ul class="nav navbar-nav">
<li><%= link_to 'Breakfast', '/breakfast', class: ('active' if request.path == breakfast_path) %></li>
<li><%= link_to 'Lunch', '/lunch', class: ('active' if request.path == lunch_path) %></li>
<li><%= link_to 'Deli', '/deli', class: ('active' if request.path == deli_path) %></li>
<li><%= link_to 'Contact', '/contact', class: ('active' if request.path == contact_path) %></li>
</ul>
Gems will not be considered an answer...
Thanks!
I'm not sure passing it into the controller is a good solution - it's concerned with view logic so I think the view is the right level to handle it on. Perhaps creating a helper method that wraps link_to would be the right approach. Here's an idea without having tested it:
# YourHelper
def nav_link_to(label, path)
link_to(label, path, class: 'active' if path == request.path)
end
You could use the active_link_to gem:
<% food = %w(breakfast lunch deli contact) %>
<ul class="nav navbar-nav">
<% food.each do |meal| %>
<li><%= active_link_to meal.titleize, eval("#{meal}_path") %></li>
<% end %>
</ul>

calling post.title in application.html.erb generates error undefined method `each' for nil:NilClass

I have sidebar in application.html.erb.
<div class="well sidebar-nav">
<h3>Rewards</h3>
<% #rewards.each do |reward| %>
<ul class="nav nav-list">
<li class="nav-header"><%= reward.title %></li>
<li><%= reward.price %></li>
<li><%= reward.image_url %></li>
<li><%= reward.details %></li>
<li><%= reward.estimated_delivery %></li>
<li><%= reward.claimed %></li>
</ul>
<% end %>
</div><!--/.well -->
I generated Rewards by: rails g scafford Rewards ....following properties.
My rewards view is working fine. but when i going on other page i get this error
undefined method `each' for nil:NilClass
I know this is because my application.html.erb is looking for #rewards in applicationcontroller and it's not there. But i dont know how to fix this issue.
If you want to have it application-wide, you should set it in before_filter of application_controller:
class ApplicationController < ActionController::Base
before_filter :set_rewards
# ...
private
def set_rewards
#rewards = #set your rewards here
end
end

rails tutorial: cookie doesn't match remember token

I am doing Michael Hartl's Rails Tutorial Chapter 8. When I try to find a user by remember_token stored in the browser cookie it isn't working. The find_by method returns NIL. I have been trying to debug by looking at the remember token cookie stored on the browser and comparing it to the remember token stored in the user database. They don't match and I don't know why. Here is the code for the Session Helper.
module SessionsHelper
def sign_in(user)
remember_token = User.new_remember_token
cookies.permanent[:remember_token] = remember_token
user.update_attribute(:remember_token, User.encrypt(remember_token))
self.current_user = user
end
def signed_in?
!current_user.nil?
end
def current_user=(user)
#current_user = user
end
def current_user
#remember_token = User.encrypt(cookies[:remember_token])
remember_token = "71e45660fbaa69bad9fb55b912f80122a584f6af"
##current_user ||= User.find_by(remember_token: remember_token)
#current_user ||= User.find_by_remember_token(remember_token)
end
end
I have been tweaking it to try and figure out what is going on. To debug I commented out the normal lines and
set the remember token explicitly with the value I see in the database - then the app works. When I compare the value of the cookie stored in the browser to the value of remember token stored in the database they don't match.
Another thing I noticed is that I can't make a call to User_find_by. I get an error that says it doesn't recognize this method so I commented it out. I can however call to User.find_by_remember_token. It is possible that I have the wrong version of something installed?
I have tried resetting the database - but I can see it and it looks like it has all the right columns.
Here is the _header.html.erb code:
<header class="navbar navbar-fixed-top navbar-inverse">
<div class="navbar-inner">
<div class="container">
<%= link_to "sample app", root_path, id: "logo" %>
<nav>
<ul class="nav pull-right">
<li><%= link_to "Home", root_path %></li>
<li><%= link_to "Help", help_path %></li>
<% if signed_in? %>
<li><%= link_to "Users", '#' %></li>
<li id="fat-menu" class="dropdown">
<a href="#" class="dropdown-toggle" data-toggle="dropdown">
Account <b class="caret"></b>
</a>
<ul class="dropdown-menu">
<li><%= link_to "Profile", current_user %></li>
<li><%= link_to "Settings", '#' %></li>
<li class="divider"></li>
<li>
<%= link_to "Sign out", signout_path, method: "delete" %>
</li>
</ul>
</li>
<% else %>
<li><%= link_to "Sign in", signin_path %></li>
<% end %>
</ul>
</nav>
</div>
</div>
</header>
It looks like the problem could be line 20 in your SessionsHelper. Should be:
#current_user ||= User.find_by(remember_token: remember_token)
Instead of passing the remember token into the User.find_by() method you're attempting to call a method find_by_remember_token, which doesn't exist.
first of all, User_find_by() isn't a method. it's User.find() or User.find_by_columnName() where columnname is the column in your database that you want to search.
also, you have to make sure your User model is defined correctly. i'm assuming you followed all the instructions til that point so you have the new_remember_token and encrypt methods and you have the create_remember_token private method? also make sure you have the before_create filter.

No route matches [GET] "/signout"

I saw a few postings related to this topic, but the given solutions did not really clarify things for me ...
So, I am working on a rails (version 3.2.2) application that followed the setup from Michael Hartl's Ruby on Rails tutorial. The application has a signout link, which worked well until recently, when it started giving me the error 'No route matches [GET] "/signout"'.
These are the relevant pieces:
routes.rb
match '/signout' => 'sessions#destroy', :via => :delete
sessions_controller.rb
def destroy
sign_out
redirect_to root_path
end
sessions_helper.rb
def sign_out
current_user = nil
cookies.delete(:remember_token)
end
_header.html.erb
<li>
<%= link_to "Sign out", signout_path, :method => :delete %>
</li>
All it takes for the signout to start working again is the removal of ":via => :delete" from the routes file. Is this the right approach or is there a better one? Also, why did the link stop working without any rails update?
Thank you,
Alexandra
On request, I added the full code for the _header.html.erb:
full _header.html.erb
<!-- ***** Initialized: Listing 5.24 ***** -->
<!-- ***** Updated: Listing 8.24 ***** -->
<!-- ***** Updated: Listing 9.7 ***** -->
<!-- ***** Begin: Listing 9.28 ***** -->
<header>
<header class="navbar navbar-fixed-top">
<div class="navbar-inner">
<div class="container">
<% if signed_in? %>
<%= link_to "project manager", about_path, id: "logo" %>
<% else %>
<%= link_to "project manager", root_path, id: "logo" %>
<% end %>
<nav>
<ul class="nav pull-right">
<!--li><%= link_to "Home", root_path %></li-->
<% if signed_in? %>
<% if Rails.env.development? %>
<li><%= link_to "Overview", overview_path %></li>
<% end %>
<% if Rails.env.development? %>
<li id="fat-menu" class="dropdown">
<a href="#" class="dropdown-toggle" data-toggle="dropdown"> Projects <b class="caret"></b>
</a>
<ul class="dropdown-menu">
<li><%= link_to "Status", projects_path %></li>
<li><%= link_to "Dev View", dev_projects_path %></li>
</ul>
</li>
<% else %>
<li><%= link_to "Projects", projects_path %></li>
<% end %>
<% if Rails.env.development? %>
<li><%= link_to "Teams", teams_path %></li>
<% end %>
<% if Rails.env.development? %>
<li id="fat-menu" class="dropdown">
<a href="#" class="dropdown-toggle" data-toggle="dropdown"> Tasks <b class="caret"></b>
</a>
<ul class="dropdown-menu">
<li><%= link_to "Status", tasks_status_path %></li>
<li><%= link_to "Tree", tasks_tree_path %></li>
<li><%= link_to "Dev View", dev_tasks_path %></li>
</ul>
</li>
<% else %>
<li id="fat-menu" class="dropdown">
<a href="#" class="dropdown-toggle" data-toggle="dropdown"> Tasks <b class="caret"></b>
</a>
<ul class="dropdown-menu">
<li><%= link_to "Status View", tasks_status_path %></li>
<li><%= link_to "Tree View", tasks_tree_path %></li>
</ul>
</li>
<% end %>
<% if Rails.env.development? %>
<li id="fat-menu" class="dropdown">
<a href="#" class="dropdown-toggle" data-toggle="dropdown"> Reports <b class="caret"></b>
</a>
<ul class="dropdown-menu">
<li><%= link_to "Project Progress", analysis_path %></li>
<li><%= link_to "Revision History", history_path %></li>
</ul>
</li>
<% else %>
<li id="fat-menu" class="dropdown">
<a href="#" class="dropdown-toggle" data-toggle="dropdown"> Reports <b class="caret"></b>
</a>
<ul class="dropdown-menu">
<li><%= link_to "Revision History", history_path %></li>
</ul>
</li>
<% end %>
<% if Rails.env.development? %>
<li><%= link_to "Help", help_path %></li>
<% end %>
<li id="fat-menu" class="dropdown">
<a href="#" class="dropdown-toggle" data-toggle="dropdown"> Account <b class="caret"></b>
</a>
<ul class="dropdown-menu">
<% if current_user.admin? %>
<li><%= link_to "Admin", users_path %></li>
<% end %>
<% if Rails.env.development? %>
<li><%= link_to "Profile", current_user %></li>
<% end %>
<li><%= link_to "Settings", edit_user_path(current_user) %></li>
<li class="divider"></li>
<li>
<%= link_to "Sign out", signout_path, :method => :delete %>
</li>
</ul>
</li>
<% else %>
<li><%= link_to "Sign in", signin_path %></li>
<% end %>
</ul>
</nav>
</div>
</div>
</header>
<!-- ***** End: Listing 9.28 ***** -->
This thread is a bit old, but I thought I'd share a solution anyway as more people might be having the same problem.
Here is some background information on how this works before we get into the actual troubleshooting:
Notice that the Sign Out link looks as follows:
<%= link_to "Sign out", signout_path, :method "delete" %>
If you look at the source code generated by this tag, you will see this:
Sign out
Notice the part that says data-method="delete". With straight HTML, this won't work. If you click the link, your browser will simply ignore the DELETE instruction and instead submit a GET request to your server (this is what you are currently seeing in your log). To get your browser to submit a DELETE request, you will need to use some JavaScript magic. This is where the jquery_ujs.js file comes in (you will most likely be able to see a link to this file by Viewing Source in your browser; it should be in the header, close to, or included within the application.js file). If you look inside the jquery_ujs.js file, towards the middle of the file, you will see the following code:
// Handles "data-method" on links such as:
// Delete
In other words, the code above makes sure that your browser actually does submit a DELETE request (we don't have to get into the details of the actual code here).
Given this background information, there are two possible reasons why you are getting your error.
You are simply missing the jquery_ujs.js file
Other JavaScript code you have written or included is interfering with the desired
behavior of the jquery_ujs.js file
To troubleshoot, do as follows:
For 1) Load the page that contains your Sign Out link and select View Source from your browser. Make sure that the file jquery_ujs.js is in the header (or concatenated with the rest of your JS files into the application.js file, depending on your application settings)
For 2) In application.js, remove the //=require_tree . directive. Reload your page, and click the Sign Out link. If the Sign Out link is hidden under a menu that only works with your JavaScript installed, then just put a duplicate of the Sign Out link somewhere else on your page where it is accessible without JavaScript. Now try clicking on the link - it should hopefully work. If you are no longer getting the routing error, you know that this was the cause for your problem. The easiest way to troubleshoot this is to add back the //=require_tree . directive, but then to remove all your JavaScript files except the application.js file from the folder where they reside, and then to add back each file one by one, while you try the Sign Out link, until it no longer works. This will allow you to identify the troublemaker JavaScript file. Once you have identified this file, try removing all code (upon which the link should work again) and then adding back pieces of the code until it no longer works - voila, you have now identified the root of the problem! Please feel free to report back what it was. My guess is that it could be either a straight up error, a return false; statement, or a stopPropagation(); statement.
Hopefully this will work! Good luck.
Since the answers that I received in September 2012 did not solve my problem, I just ended up removing ":via => :delete" from the routes file, which made the signout link work again.
After reading eriklinde's answer, I went back to my code to see if his answer would help. The jquery_ujs.js file was not missing. So, I started looking into the second possible reason that was suggested. Nevertheless, when I went to the routes.rb file and added "via: :delete" to have a line reading "match '/signout', :to => 'sessions#destroy', via: :delete", the signout functionality continued working without a problem. Since "via: :delete" is different than ":via => :delete", which I previously removed, maybe this was causing the problem?
I think the solution is here:
Rails 3 link_to (:method => :delete) not working
Are you missing <%= javascript_include_tag :all %> in your page? It should go in your layout file.
I had this same problem and fixed it by rearranging the order of the requirements in the application.js file. Mine were ordered as such:
//= require jquery_ujs
//= require jquery
//= require bootstrap
//= require_tree .
and are now ordered like this
//= require jquery
//= require jquery_ujs
//= require bootstrap
//= require_tree .
I literally did nothing else.
try changing the _header.html.erb partial to
<li>
<%= link_to "Sign out", signout_path, :method "delete" %>
</li>
Actually you are probably missing the cross site forgery protection tags. Which would explain the inability to delete via the delete method. Not sure why it was working before.
Add this to your layout file in the head section
for haml
= csrf_meta_tags
for erb
<%= csrf_meta_tags %>
My guess would be that somehow you don't have jQuery UJS installed / active.
One of the key features listed here is "make non-GET requests from hyperlinks." Try adding gem 'jquery-rails' to your gemfile, run bundle install from the command line, restart your server, and see if it works!
This should be in your application.js file (with no lines above it that don't start with //!)
//= require jquery
//= require jquery_ujs
try this :
just add into you application.js
//= require jquery_ujs

How do I apply an 'active' class to my navigation based on the current_page in a DRY way? - Rails 3

So in my application.html.erb I have my navigational structure that looks something like this:
<div id="navigation">
<ul class="pills">
<% if current_page?(:controller => 'welcome', :action => 'index') %>
<li><%= link_to "Profile", vanity_path(:vname => current_user.username) %></li>
<li><%= link_to "Settings", settings_path %></li>
<li><%= link_to "Sign Out", signout_path %></li>
<% elsif !current_page?(:controller => 'welcome', :action => 'index') %>
<li><%= link_to "Home", root_path %></li>
<li><%= link_to "Profile", vanity_path(:vname => current_user.username) %></li>
<li><%= link_to "Settings", settings_path %></li>
<li><%= link_to "Sign Out", signout_path %></li>
<% end %>
</ul>
</div>
However, what I would like to do, is once they are on any of the pages in the navigation, it applies a class active to the respective link.
So for instance, if the user is on mydomain.com/johnbrown which is the Profile link, the rails helper would look something like this:
link_to "Profile", vanity_path(:vname => current_user.username), :class => "active".
But how do I do that in a programmatic way, so I am not duplicating content? i.e. how do I get that functionality for all the pages in my navigation and write it as DRY as possible?
Thanks.
This is a really great question. I've never really been happy with the solutions I've seen or come up with. Maybe we can get one together here.
Here is what I've tried in the past
I've made a helper that returns a hash with :class defined since I use HAML
def active_tab(path)
request.path.match(/^#{path}/) ? { :class => 'active' } : {}
end
ex usage:
= link_to "Dashboard", dashboard_path, active_tab("#{dashboard_path}$")
Or an alternative along the same lines
def active_class(path)
request.path =~ /#{path}/ ? 'active' : nil
end
ex usage:
= link_to 'Presentations', admin_presentations_path, :class => "#{active_class('presentations')}"
I would love to see some other suggestions on this.
I found this answer for a bootstrap related navbar but you could easily use it with your nav.
Answer taken from here
You can use helper for handle "current_page?", example a method :
module ApplicationHelper
def is_active?(link_path)
if current_page?(link_path)
"active"
else
""
end
end
end
example bootstrap navbar
<div class="navbar">
<div class="navbar-inner">
<a class="brand" href="#">Title</a>
<ul class="nav">
<li class="active">Home</li>
<li>Link</li>
<li>Link</li>
</ul>
</div>
</div>
So, on view looks like
<li class="<%= is_active?(some_path) %>">
<%= link_to "name path", some_path %>
</li>
For Haml
Just simple looks like :
%ul.nav
%li{class: current_page?(some_path) && 'active'}
= link_to "About Us", some_path
You may define a helper method in application_helper.rb
def create_link(text, path)
class_name = current_page?(path) ? 'my_class' : ''
content_tag(:li, class: class_name) do
link_to text, path
end
end
Now you can use like:
create_link 'xyz', any_path which would render as
<li class="my_class">
xyz
</li>
Hope it helps!
Why don't you just take the redundant parts out of the if else block? Also take a look at 'link_to_unless'
<div id="navigation">
<ul class="pills">
<li><%= link_to_unless(current_page?(:controller => 'welcome', :action => 'index'), "Home", root_path %></li>
<li><%= link_to "Profile", vanity_path(:vname => current_user.username) %></li>
<li><%= link_to "Settings", settings_path %></li>
<li><%= link_to "Sign Out", signout_path %></li>
</ul>
</div>
then I would add some jQuery to inject active class into the link that matches the window.location pattern.

Resources