Ruby on Rails: Wrong number of arguments troubleshooting - exception

Ok, I know this sounds like a question already asked, but please trust me and read on.
I am writing a Rails 4 application. I have a Comments class that can apply to multiple other classes (client, project, etc.). The idea is, I pass a parent object as follows:
"<%= link_to "Add comment to #{#audit.name}", new_comment_path(audit_id: #audit.id) %>"
Within my comments controller, I have logic to determine how to assign the comment.
I also allow parameters as follows:
def comment_params
params.require(:comment).permit(:narrative, :version, :last_updated_by, :support, :client_id, :control_id, :test_id, :step_id, :audit_id)
end
What is defeating me is, I get the 'wrong number of parameters: 1 for 0' error when I click the link defined above, with the error pointing to the comment_params code as the problem. I thought that the point of the comment_params method was to work out what to allow (and note: audit_id is on the list of allowable parameters). However, it appears that this method is not accepting parameters. The error has to be simple and syntactic, but I cannot figure it out.
My questions are 1) how would I diagnose this issue and 2) what have I misunderstood with regard to passing parameters, if such is obvious to the more experienced among you? I am flat out of ideas, and Google / SE results generally show problems understanding what the error means, which I don't think is the problem here. I have read and understood the error, but not enough to actually fix it - the problem is with the code that actually defines acceptable parameters!
Thanks in advance.

Related

Prevent quotes to be saved in DB as HTML-entities after sanitization

This might be a stupid question but after all the research on best practices – including this great SO post that explains sanitizing, validation, escaping for storage and escaping for display – I am still confused.
I have built a routine where I sanitize user input – say, a comment post, or "edit my first name" string – with $value = filter_var($value, FILTER_SANITIZE_STRING);. Given a value of O'Hara, that gets rid of <a></a> and similar tags nicely. Then this new value gets validated: error if empty value and field is not nullable; or if too long; etc. Lastly, I save that value in the DB using a CakePHP query builder – which, of course, supports binding string values.
But when I then save that value in the DB, it is saved as O'Hara instead of O'Hara – because of said sanitization.
Am I supposed to decode it back / to yet another format? If so with which method?
Or, am I to use the sanitized version for validation but then the original value for DB stora-- that can't be it.
Or is FILTER_SANITIZE_STRING a flag I need to tweak? The tutorials I've seen [1] [2] suggest that the flag is enough.
I feel so dumb because that great post mentioned earlier seems to still not be enough for me. All I can find are posts from ~2012 that say you should bind.
Any help would be appreciated.

How to identify "throw exceptions" in a Java program regarding Integer.parseInt method

I am new to Java and I am having trouble understanding a question. I am asked to select which of the following choices throws an exception. The options are:
1.) Integer.parseInt(" ")
2.) Integer.parseInt("54 ")
3.) Integer.parseInt("")
4.) Integer.parseInt("-54")
5.) Integer.parseInt("54n")
To answer this question, I need some explanations. What does the Integer.parseInt method do? Doesn't it turn an integer into a String? What sort of arguments are illegal to put inside this method. For example, are you allowed to include negative numbers? Strings? Or does it only accept integers?
I was also wondering if you could clarify what "throws an exception" means. I have a rough idea, I think it just means that if there is an error in your program, it gets terminated. Howevere, you can use the "try-catch-finally" method to try and predicate any errors your program would have and write a possible code to fix it?
Sorry for all the questions, I just want to understand this completely.

Django order_by() is not working for me on PythonAnywhere

For some reason order_by() is not working for me on a queryset. I've tried everything I can think of, but my Django/MySQL installation doesn't seem to be doing anything with order_by() method. The list appears to just remain in a fairly unordered state, or is ordered on some basis I cannot see.
My Django installation is 1.8.
An example of one of my models is as follows:
class PositiveTinyIntegerField(models.PositiveSmallIntegerField):
def db_type(self, connection):
if connection.settings_dict['ENGINE'] == 'django.db.backends.mysql':
return "tinyint unsigned"
else:
return super(PositiveTinyIntegerField, self).db_type(connection)
class School(models.Model):
school_type = models.CharField(max_length=40)
order = PositiveTinyIntegerField(default=1)
# Make the identity of db rows clear in admin
def __str__(self):
return self.school_type
And here is the the relevant line from my view:
schools = School.objects.order_by('order')
At first I thought the problem was related to having used the non-standard PositiveTinyIntegerField() defined by a class I found on a website somewhere which allows me to use the MySQL Tiny Integer field. However, when I ordered by 'id', or 'school_type' the list still remained in an order that appeared fairly random to my eye.
I could put in my own loop which orders the queryset after it has been retrieved, but I'd really rather solve this issue so I can use the standard Django way of doing it.
I hope someone can see where the issue may be coming from.
I managed to resolved it with some help from the comments here. I tried writing the school object to stdout using sys.write.stdout(str(school)). The logs then showed me that in fact the data was being ordered correctly, so the problem had to be with how the data was being packaged before being rendered by the template.
I wrote the view some time ago before I decided I wanted it ordered, so it turned out the problem was caused by each school object (with an attached tree of related data) being read into a dictionary. Once I changed the data type to the list, the schools then rendered in my intended order.

Why does $my_item->save fail with Rose::DB::Object?

I am trying to do a simple addition of data to a database table (PostgreSQL). At first, I couldn't even get a simple
$my_item = $_item_class->new(...);
to work. I discovered I had spelled a field differently in my code from what I had in my "model" code.
But, now, this is working, but when I try:
$my_item->save;
it seems an exception is thrown. All this is occurring in an eval {...} structure and I would like to catch the exception and see what is going wrong, but I don't know how to do that.
Why would something like the "save" be failing here? I have checked everything, and all seems right (of course!).
And, how do I catch the exception that seems to be being thrown?
Thank you!
I figured all this out myself. It was simple. I had duplicated a field in my class somehow when I had done an edit to it. That was all. The class just had two identically named fields specified in the hash table in the class, both with identical characteristics. When I removed one of these, the code worked.
With regard to my second question about how to catch the exception, I had to learn how to have an
if ($#) {
.
.
.
}
right after my "eval {...}" structure. Because I am new to Perl, I didn't understand that. But, it was actually pretty easy to figure out. My problem was that I was working from some code as a model for me that didn't do that but named specific exceptions that were thrown in its "eval {...}" code. So, I thought that I had to have the names of exceptions that could be thrown by Rose::DB::Object calls, but I couldn't find any such exceptions in the documentation. When I learned about "if ($#) {...}", I was able to print out the reported exception in $# and from that I was able to see the problem with the duplicate field I mentioned above.
That was all there was to it. Everything is working just fine now.

Deal with undefined values in code or in the template?

I'm writing a web application (in Python, not that it matters). One of the features is that people can leave comments on things. I have a class for comments, basically like so:
class Comment:
user = ...
# other stuff
where user is an instance of another class,
class User:
name = ...
# other stuff
And of course in my template, I have
<div>${comment.user.name}</div>
Problem: Let's say I allow people to post comments anonymously. In that case comment.user is None (undefined), and of course accessing comment.user.name is going to raise an error. What's the best way to deal with that? I see three possibilities:
Use a conditional in the template to test for that case and display something different. This is the most versatile solution, since I can change the way anonymous comments are displayed to, say, "Posted anonymously" (instead of "Posted by ..."), but I've often been told that templates should be mindless display machines and not include logic like that. Also, other people might wind up writing alternate templates for the same application, and I feel like I should be making things as easy as possible for the template writer.
Implement an accessor method for the user property of a Comment that returns a dummy user object when the real user is undefined. This dummy object would have user.name = 'Anonymous' or something like that and so the template could access it and print its name with no error.
Put an actual record in my database corresponding to a user with user.name = Anonymous (or something like that), and just assign that user to any comment posted when nobody's logged in. I know I've seen some real-world systems that operate this way. (phpBB?)
Is there a prevailing wisdom among people who write these sorts of systems about which of these (or some other solution) is the best? Any pitfalls I should watch out for if I go one way vs. another? Whoever gives the best explanation gets the checkmark.
I'd go with the first option, using an if switch in the template.
Consider the case of localization: You'll possibly have different templates for each language. You can easily localize the "anonymous" case in the template itself.
Also, the data model should have nothing to do with the output side. What would you do in the rest of the code if you wanted to test whether a user has a name or not? Check for == 'Anonymous' each time?
The template should indeed only be concerned with outputting data, but that doesn't mean it has to consist solely of output statements. You usually have some sort of if user is logged in, display "Logout", otherwise display "Register" and "Login" case in the templates. It's almost impossible to avoid these.
Personally, I like for clean code, and agree that templates should not have major logic. So in my implementations I make sure that all values have "safe" default values, typically a blank string, pointer to a base class or equivalent. That allows for two major improvements to the code, first that you don't have to constantly test for null or missing values, and you can output default values without too much logic in your display templates.
So in your situation, making a default pointer to a base value sounds like the best solution.
Your 3rd option: Create a regular User entity that represents an anonymous user.
I'm not a fan of None for database integrity reasons.