rails 4.1 undefined method for nil class - ruby-on-rails-4.1

Hi I am trying to show the current users friend list / or the friends that might be pending, but i got an error like this one
NoMethodError in UserFriendships#index
undefined method `each' for nil:NilClass
this is what is was showing to give out the error
<% #user_friendships.each do |friendship| %>
This is my code in the controller
before_filter :authenticate_user!
def index
#user_friendship = current_user.user_friendships.all
end
this is my code in the index
<% #user_friendships.each do |friendship| %>
<% friend = friendship.friend %>
<div id="<%= dom_id(friendship) %>" class="friend now">
<div class="span1">
<%= link_to image_tag(friend.gravatar_url), profile_path(friend) %>
</div>
</div>
</div>
<% end %>
I have already defined the #user_friendship in my controller but it seems that its not working properly I am a bit new here and getting things together, but this error keeps me from going forward, if anybody can help me that would be great!

Rails cannot see your defined method user_friendships on current_user, hence #user_friendship is nill.
For your use, you would need to only call id directly on current_user, like
#user_id = current_user.id
Then, you can search the database for the User with this particular id
#current_user = User.find(#user_id)
So, you can get any method this new #current_user, in your case;
def index
#user_friendship = #current_user.user_friendships.all
end
And proceed with the list
<% #user_friendships.each do |friendship| %>
Rails is an MVC framework, meaning Models, Views, and Controllers. The Models primarily, enables communication between the database (like MYSql) and the controllers. Views are basically what the users see (like HTML, CSS), they communicate and grasp needed data through the Controller. And the Controller does the most work. The Controller takes in requests from the user, points the request through a model to the database, and returns the result to the view. All these are done by the Controller with the help of the server. For further explanations on Rails MVC framework and MVC generally, please checkout these links
How are Model, View and Controller connected?
What is MVC in Ruby on Rails?
http://betterexplained.com/articles/intermediate-rails-understanding-models-views-and-controllers/
http://www.codelearn.org/ruby-on-rails-tutorial/mvc-in-rails
http://blog.codinghorror.com/understanding-model-view-controller/

Related

ASP 4.0 get values from session

im trying to find the contents of the session in a webpage im working on.
But since im not a programmer i have to revert to copy paste code i find online...
I dont know what variables are set in the session, thats why i want to know how many and what variables there are.
Now i found the following
<font face=arial size=1>
Session Variables - <% =Session.Contents.Count %> Found<br><br>
This works like a charm. It finds 7 to 12 values in the session. But when i try to follow up WHATS inside the session...
<%
Dim item, itemloop
For Each item in Session.Contents
If IsArray(Session(item)) then
For itemloop = LBound(Session(item)) to UBound(Session(item))
%>
<% =item %> <% =itemloop %> <font color=blue><% =Session(item)(itemloop) %></font><BR>
<%
Next
Else
%>
<% =item %> <font color=blue><% =Session.Contents(item) %></font><BR>
<%
End If
Next
%>
my page crashes with: CS1044 (and the dutch translation)
Since part 1 worked of the code i assumed that part 2 would work too.
Could anyone please help?
Seems that i needed to use Visual Studio 2015 (community edition) to find my answer for at least part of the question.
Hightlighting the string with what seemd to be a session variable (user.firstname) took me to user.cs (using F12) where i could find the other variables.
Hope this helps someone...

Undefined Method in HTTParty class

I'm somewhat new to rails and every time I think I'm getting it I hit a wall.
I'm using HTTParty and this API. I am just trying to get a response to show up in my index view to get the lowest level of the api working.
It worked for me in the console but not when I tested it in the API. I'm getting an
undefined method `picture' for Snapshots:Class
error for my index view.
Here is the HTTParty class
class Snapshots
include HTTParty
def initialize
#sitename = "google.com"
end
def picture
response = HTTParty.get("http://api.snapito.com/web/516e011353b62078731712566b01e143f56adf0b/full/diditmatter.herokuapp.com/lists")
if respone.success?
response
end
end
end
Here is my lists controller
def index
#it_works = Snapshots.picture
respond_with(#lists = List.all)
end
And here is list view
<%= #it_works %>
<h1 class="page-header">Projects at a glance</h1>
<div class="span12 offset2">
<% #lists.each do |list| %>
<div class="well row span4">
<div class="span3">
</div>
<div class="span4">
What do I seem to be overlooking here?
EDIT
#Benjamin fix worked, but I've come across a problem I'm not sure is related to rails. I'm not sure is I should open another question. But since the context is here and I'm not really even sure how to search this, I have to follow up here.
That instance variable is returning the attached screen shot. Is this related to how I'm calling it from the API I linked to in the first paragraph?
I've never seen this so not to sure where to look or how to approach.
You are treating the picture method as a class method. Change it to this: #it_works = Snapshots.new.picture

Error handling for ASP based sites and forms

I'm working on a asp based (not .net) site, which spans about 400 odd pages... Now, throughout the site there're ASP and VBScript errors, such as:
Microsoft VBScript runtime error '800a000d'
Type mismatch: 'Cdate'
/MySite/page.asp, line 71
(The above happened when I put in characters into a 'date' field. I know its VBScript in this case, but I get plenty all over.)
Now, I know I can avoid this scenario with client side validation (jQuery for example), but when such things do happen, how do I code up a default 'error' page? You hit the error, and instead of showing you the above, you get redirected to a generic 'error' page?
I've looked up some of this, and found the ASP 'On Error Resume Next' thing, but I haven't found any viable examples. Each one is tailored to a specific error (like dividing 5 by 0), and I really don't want to code up like 400+ potential error messages.
You could create custom error pages, via IIS. I'm not sure what version you're running, etc - but this should give you a good jumping off point. http://support.microsoft.com/kb/224070
You add following code in top in your page.
<% on error resume next%>
.
..
....
(Other code is above instead of point(.))
Then you add
<% if err then
response.redirect("err.page?code="&err.code)
end if%>
And you define error message in your generic error page according to error number.
if you ask same question for client side. You can try and catch code block for possible code clock that will can throw.
For examle
<script language="text/javascript">
try
{
//Code that will can throw error is here.
}
catch(err)
{
document.href.location="genericerrorpage.asp?err=" + err.code;
}
}
</script>

Object reference not set while SQL manager says it is

Lately I have run in a strange NullReferenceException. It pops up only occasionally why it is so hard to debug it for me. Today it happened again and I want to fix it now I have the error.
I have the following setup:
An asp.net view with relevant code:
<%# Control Language="C#" Inherits="System.Web.Mvc.ViewUserControl<WerkStageNu.Profiles>" %>
<%# Import Namespace="WerkStageNu.Helpers" %>
<div class="listing">
<div class="content">
<h3><%=Html.ActionLink(Model.Persons.UserName, "Details", new { id = Model.ID } )%></h3>
And when running this it tells me that Model.Persons is null giving the following error, while the Model itself is loaded with the data from the (SQL) Database. I am using ADO.net entities. Retrieving the profile instead of using the model resulted in the same error.
<%=Html.ActionLink(WerkStageNu.Models.Repository.Instance.GetProfileByID(Model.ID)
.Persons.UserName, "Details", new { id = Model.ID } )%>
Did not do any good.
Some error images:
debug mode http://www.bastijn.nl/zooi/model_persons.png
stack trace http://www.bastijn.nl/zooi/stacktrace.png
So far it seems a normal error, but when I checked my DB behind the request I found that this field is filled in and that the link is correct. SQL manager screens to show this information:
Profiles table:
profiles DB http://www.bastijn.nl/zooi/profiles_sql.png
Persons table:
persons DB http://www.bastijn.nl/zooi/persons_sql.png
As one can see all the PersonIDs are set so normally all the links should be loaded? Sometimes this is the case, but sometimes however this nullreference pops up from out of nowhere. Am I forgetting something? Should I manually load something?
//edit
I notice
<% Model.PersonsReference.Load(); Model.EmploymentsReference.Load(); %>
Fixes this problem, the question is why I need it here and not throughout the rest of my views using the same approach?
It could be related to lazy loading the Persons collection.
I notice
<% Model.PersonsReference.Load(); Model.EmploymentsReference.Load(); %>
Fixes this problem, the question is why I need it here and not throughout the rest of my views using the same approach?

Math.sqrt(-5) -> Force Exception in JSP?

I've 3 .jsp files. index.jsp and sqrtcalculator.jsp and error.jsp.
In index.jsp there's a text field and a button. In sqrtcalculator.jps there's the, well, calculator.
Now, when I leave the field empty and press the button, an expection is called, because the field is empty. And I can then reroute to an individual error.jsp site to display the errors, and exception stack like
<%= request.getAttribute("javax.servlet.error.request_uri") %>
<%= exception.getMessage() %>
<%= exception %>
etc.
Problem is, when I enter -5 in the textfield, I can't get an exception, because Math.sqrt(-5) doesn't return an error but "NaN".
How can I force it to be an exception? The idea is to reroute the user to an individual error.jsp and displaying the errors. But like I said Math.sqrt(-5) doesn't return errors or exceptions but "NaN" textstring.
I don't want something like this just FYI
<%if (NaN){
%>
<p>Nope, Square root from negative numbers is not defined!</p>
<%}
%>
Warning, the test for NaN in the previous answer is wrong (NaN is NOT equal to itself). In Java the better way to test for NaN is
if (Double.isNaN(answer)) {
// throw exception
}
alternatively
if (answer != answer) {
}
While this second version will work, it is sure to puzzle those not aware of the curious behaviour of NaN.
How about:
if (x >= 0.0) {
return Math.sqrt(x);
} else {
throw new ArithmeticException("Square root from negative numbers is not defined!");
}
Note that ArithmeticException is a subclass of RuntimeException and therefore does not need to be declared in the throws clause of your function.
It's presumably returning NaN because square roots of negative numbers are indeed defined, they're just not real numbers. Is there any reason you can't do this?
if(Double.isNaN(answer))
throw new ArithmeticException("Answer unreal");
That should tickle your exception handling code, but the source line might just be a few lines off. I've never written JSP, but that makes sense in Java.
I'm not very good in jsp but afaik you should be able to use basic java code.. so i'd check my result for NaN and throw an exception
if (NaN == result)
throw new Exception("NaN");
you'll have to adjust the if ;)
I would ask why you're using scriptlets in JSPs.
If your app really is just three pages (index.jsp and sqrtcalculator.jsp and error.jsp), then maybe it's justifiable.
But my general recommendation would be to stay away from scriptlet code in JSPs and prefer JSTL. Have those calculations done in a server-side component, using a Model-2 MVC arrangement.
If your app really consists of only three pages, re-architecting it to use Model-2 MVC would not be difficult to do. You might find that it's far more extensible that way. If you're unfamiliar with Model-2 MVC you can read about it here. If you're familiar with it, this might be a self-contained problem that's small enough to let you see where it could provide some value in future projects.
Another thought would be to add complex numbers to your calculator, because the square root of negative numbers is indeed a valid concept. It just requires imaginary numbers. Maybe your calculator needs to be extended to maximize usefulness.
I can't seem to get it to work....
if (d < 0){
throw new Exception("Negative Numbers not possible!");
}
d is a double read via d_string = request.getParameter("numberfromtextfield") and converted to double via double d = Double.parseDouble(d_string);.
This is what Eclipse is telling me: http://pastebin.ca/1691409

Resources