Showing posts with label errors. Show all posts
Showing posts with label errors. Show all posts

Friday, October 28, 2011

Require - No Such File to Load Ruby

The exercise I'm working through in Learn Ruby the Hard Way has me spending a week creating my own game. I've been building various text-based adventure games, but was stuck on what to do next. This morning on the way to work I got the idea of building a MadLib generator.

The way I picture it working is like this: the generator will ask the user to select a Mad Lib from a list, then ask for the requisite input (nouns, adjectives, verbs) depending on the Mad Lib selected and finally spit out the finished product. Simple, right?

So my thinking is this project would be split into two parts: the main program that asks for which Mad Lib the user wants to do, and the Mad Lib that is loaded upon selection. To get this up and running, I decided just to make one Mad Lib work at first, then add support for multiple Mad Libs and the ability to choose between them.

This is just a simple matter of requiring the Mad Lib file from the Main file, but I ran into a small problem.

Using the require 'mermaid' command threw this error:

<internal:lib/rubygems/custom_require&rt;:29:in `require': no such file to load -- mermaid (LoadError)

I wasn't sure why this wasn't working, since I've used require to load separate .rb files before. After a bit of digging around, all I had to to do fix this problem is change require 'mermaid' to require_relative 'mermaid'. This makes sense - both files are in the same directory, so this command is simply saying to require this file located in the same directory as the main file.

On a side note, I'm glad to have fixed the problem, but I'm getting to the point that I think it's better to understand WHY things don't work, rather than finding the solution and moving on. Can anyone tell me why 'require' wasn't working, but 'require_relative' does? Is it an older style of Ruby code that's outdated? Do I need to change some configurations? Is require_relative a workaround? Where does require look for files, if not in the same directory the file that's making that call is located?

Anyway, it felt good to make some progress on this tonight. It's pretty awesome that I can come up with an idea on the way to work, come home and put it together in an hour and a half or so. I think this will be a fun little project. I plan to work on it more this weekend, expanding it, polishing it up and so on. Here's a link to the gist I made of it:

MadLib Generator

Sunday, September 18, 2011

Nil can't be coerced into Fixnum in Rails

Question time!

I'm trying to figure out a way to calculate bonuses or penalties from a Character's Statistics, and then apply that method in other Models' views to calculate things like Fortitude saves, attack bonuses and so on. I've been working with a modifier for Constitution and here's what I've got so far.

The logic for calculating a Statistic bonus/penalty is (statistic - 10) / 2. So for a score of 14, we get 2, and for a score of 8, we get -1. Not bad so far!

So I define this method in Statistic controller:

def con_modifier
  (constitution.to_i - 10) / 2
end

And since I want to see it in my Character view, I wire it up in the Show method in Characters controller as such:

@con_modifier = @character.statistic.con_modifier

So I can see it in my Character view (where most of this information is displayed) and I know it's working so far. I've got a Fortitude model for Fortitude saves, and I'd like to use the con_modifier in the logic to calculate a total. How do I call a foreign model correctly this way? I have:

Here's the logic for calculating a total in my Fortitude model right now:

def total
  fortitude_base.to_i + ability.to_i + magic.to_i + misc.to_i
end

And I tried changing it to:

def total
  fortitude_base.to_i + @con_modifier + magic.to_i + misc.to_i
end

But then I get this error:

nil can't be coerced into Fixnum

So obviously it isn't calling up the correct information. I've noticed if I chage @con_modifier to @con_modifier.to_i, it calculates it at 0, because it's nil. Any ideas on how to call the number that actually exists? Do I need to define it in my Fortitudes controller as well, or can I simply define it in the Fortitude model and call it in the view that way?

Tuesday, August 16, 2011

Validation errors in Rails

Whoa! I've been chugging along with Manticore the last 5 days or so and making some good progress. However, I've hit another wall (can you believe it?)

Basically here's the problem. I have a model Ac that creates Armor information for a Character. I've created some methods to calculate various data from fields from a Character's Ac model, and to avoid any errors when doing these calculations I need to validate presence_of and numericality_of several fields.

So my problem is two-fold. First off, when creating the Ac, all of the validation errors appear before the user has attempted to enter any data. Furthermore, the user can still create an Ac with no data at all. Clearly my validation isn't working.

Here's the code itself from my Ac model:

class Ac < ActiveRecord::Base
belongs_to :character
validates_presence_of :base_ac, :armor, :shield, :dex, :size, :natural, :misc, :deflection validates_numericality_of :base_ac, :armor, :shield, :dex, :size, :natural, :misc, :deflection

...
end


And the code from my AcsController:

class AcsController < ApplicationController
def new
  @character = Character.find(params[:character_id])
  @ac = @character.create_ac(params[:ac])
end

def edit
  @character = Character.find(params[:character_id])
  @ac = @character.ac
end

def create
  @character = Character.find(params[:character_id])
  @ac = @character.ac(params[:ac])
  redirect_to character_path(@character), :notice => 'Armor Class was successfully created.'
end

def update
  @character = Character.find(params[:character_id])
  @ac = @character.ac
  if @ac.update_attributes(params[:ac])
    redirect_to character_path(@character), :notice => 'Armor Class was successfully updated.'
  else
    render :action => "edit"
    end
  end

end

I'm not sure what could be causing this problem. I've got similar validation for the Character model and it works fine. Any advice? The form_for a new Ac is rendered from a partial in the Character show page, but I'm not sure if that would have an effect on this.

Also, on a slightly tangential note, when rendering a form like this, is that what's meant by a "nested form" ? I've seen this term a few times while searching for a solution and I'm unclear as to what it means.

Here's a link to the project on Github: https://github.com/illbzo1/Manticore

Sunday, July 31, 2011

More Routing Issues in Rails

I've made some progress with Manticore this weekend, but I've hit another wall. Surprise!

Thanks to @unixmonkey and @jqr, I can now add, view and destroy items, linking to the items index page from a menu partial that is called from the character's show page. Success! However, I thought it might be handy to be able to edit items. And that's where my problem comes in. For a while, I was getting a routing error. Then I edited the code and now I'm getting this old chestnut again:

undefined method `item' for #<Character:0x103f0ce50>

What gives? I thought I'd gotten rid of this guy when I defined the character in the items controller.

Here's my edit method from the items controller:

  def edit
   @character = Character.find(params[:character_id])
   @item = @character.item
  end

  def update
    @character = Character.find(params[:character_id])
    @item = @character.statistic
    if @item.update_attributes(params[:item])
      redirect_to character_items_path, :notice => 'Item was successfully updated.'
    else
      render :action => "edit"
    end
  end

And here's how I'm calling it from the partial I created for creating and editing items:

<%= link_to 'Edit', edit_character_item_path(@character, item) %>

Any more tips? I'm pretty sure I'm just not writing this correctly. This code is based on what I've got for my other models (statistics, armor class, etc) but I wonder if it might be different based on a couple of things. For one thing, those other models have a has_one relationship with Character, while Items has a has_many. For another, the has_one models are all displayed in the Character show page, while Items is being created from the Items index page. Am I on the right track here? Any advice as to how to solve this issue?

On a less begging for help note, I've spent a good 5 hours working on Manticore this weekend. I notice when I'm working on a personal project and not a tutorial, I can focus for longer periods of time and I find the work more interesting. When doing a tutorial, I feel like it's a valuable use of my time but it's not an interesting use of my time. Does that make sense? Regardless, I absolutely lose track of time when working on my own projects, even if it's just repeatedly butting my head up against trying to get a goddamn edit method to work.

Saturday, July 30, 2011

Models, forms and view pages in Rails

I'm back to working on Manticore after a couple months away doing tutorials. I've made some progress this afternoon, but now I've run into a snag.

Here's what's going on: I have two models, Character and Item. I've created a form_for new Items that belong to a Character. The form works fine when displayed in the Character view, but what I want to do is move the form and Item listing out of the Character view and into the Index page of Item, so I can link to it from the Character view. I've got a _menu partial that I'll be using to display other views relating to Character, such as Skills, Spells, Items and so on. I'm not sure what the issue is, but simply transplanting the code as is gives me this error:

undefined method 'items' for nil:NilClass

Here's the exact code I'm using:

<h2>Add an item:</h2>

<%= form_for ([@character, @character.items.build]) do |f| %>
  <div class="field">
    <%= f.label :name %><br />
    <%= f.text_field :name %>
  </div>
  <div class="field">
    <%= f.label :type %><br />
    <%= f.text_field :type %>
  </div>
  <div class="field">
    <%= f.label :location %><br />
    <%= f.text_field :location %>
  </div>
  <div class="field">
    <%= f.label :description %><br />
    <%= f.text_area :description %>
  </div>
  <div class="actions">
    <%= f.submit %>
  </div>
<% end %>

<table>
<% @character.items.each do |item| %>
  <tr>
    <td><%= item.name %></td>
    <td><%= item.type %></td>
    <td><%= item.location %></td>
    <td><%= item.description %></td>
  </tr>
  <table>
<% end %>

Like I said, this works just fine in the character/show page, but does not work when placed in item/index and linked to from my _menu partial. Any ideas?

Here's a link to my git repository:

Sunday, July 24, 2011

More Heroku Rails Deployment Issues

I've (partially) fixed my issues with deploying to Heroku. The solution was to specify rake version 0.8.7, as noted all over Stack Overflow for people who had the same error I was getting. I could have fixed this issue earlier, if I'd realized you deploy to Heroku from Git, not from your local machine. So I was updating my code, then trying to migrate the database on Heroku and I kept getting the same error because the code hadn't been changed on Git. Still, progress!

But I'm still having a problem. Take a look at the deployed version of my Depot application:


And here's a screenshot of how it looks on my machine:


Heroku is not displaying the product listing and I can't figure out why. The database information is stored in a seed file, so I thought a heroku rake db:seed command would populate the data and fix my issue, but no such luck. I've also noticed that the new action for my Product model throws an error on Heroku, but it works on my local version. Any ideas what's going on here?

Here's a link to my git repository for this application:

Saturday, July 23, 2011

Uninitialized Constant Rake::DSL and Heroku

I took @jqr's advice and signed up for Heroku this morning. Agile Web Development had me working on running a virtual name server with Apache and it was way too complicated for my tastes. Apparently coders who don't want to deal with server-side headaches are pretty common, hence Heroku!

But I've hit a snag. I get an uninitialized constant Rake::DSL error whenever I try to run a migration on Heroku. Here's the full error:

gozer /users/tylermoore/code/depot master$ heroku rake db:migrate
(in /app)
rake aborted!
uninitialized constant Rake::DSL
/usr/ruby1.9.2/lib/ruby/1.9.1/rake.rb:2482:in `const_missing'
/app/Rakefile:6:in `'
/usr/ruby1.9.2/lib/ruby/1.9.1/rake.rb:2373:in `load'
/usr/ruby1.9.2/lib/ruby/1.9.1/rake.rb:2373:in `raw_load_rakefile'
/usr/ruby1.9.2/lib/ruby/1.9.1/rake.rb:2007:in `block in load_rakefile'
/usr/ruby1.9.2/lib/ruby/1.9.1/rake.rb:2058:in `standard_exception_handling'
/usr/ruby1.9.2/lib/ruby/1.9.1/rake.rb:2006:in `load_rakefile'
/usr/ruby1.9.2/lib/ruby/1.9.1/rake.rb:1991:in `run'
/usr/ruby1.9.2/bin/rake:31:in `

'


Apparently, this is a well-documented error, and I've dug through a ton of Stack Overflow and Google discussion threads, trying various solutions but no luck so far.

I've manually set my rake gem to version 0.8.7, updated my GemFile and pushed changes to Git, which works for a lot of people, but not for me. Still, I'm not discouraged. I'll figure this out eventually. Just thought I'd throw this up here in case someone has had this exact error and found another solution.

Monday, July 11, 2011

Editing Functional Tests in Rails

There was a time I was afraid of breaking my code. And then there was a time I was less afraid of breaking my code, but I became obsessed with fixing every little error and bug that I ended up wasting time on something relatively trivial when I could be working on more productive matters.

Case in point:

I've been working through the Depot application with Agile Web Development with Rails. This latest chapter had me working through creating a mailer and writing tests for it. Creating the mailer went well, and I can use my own gmail account to send mail through my Depot application! SUCCESS!

However, I got hung up on the functional tests. And I know what the problem is, but not how to fix it.

Here are the errors I get:

1) Error:
test_should_destroy_line_item(LineItemsControllerTest):
ActiveRecord::RecordNotFound: Couldn't find LineItem with ID=980190962 [WHERE ("line_items".cart_id = 980190963)]
app/controllers/line_items_controller.rb:79:in `destroy'
  test/functional/line_items_controller_test.rb:45:in `test_should_destroy_line_item'
  test/functional/line_items_controller_test.rb:44:in `test_should_destroy_line_item'

2) Error:
test_order_shipped(NotifierTest):
ActionView::Template::Error: undefined method `protect_against_forgery?' for #<#:0x1030519d8>
    app/views/line_items/_line_item.html.erb:9:in `_app_views_line_items__line_item_html_erb___1505233713_2172764620_6072364'
    app/views/notifier/order_shipped.html.erb:8:in `_app_views_notifier_order_shipped_html_erb___2127495373_2172826120_0'
    app/mailers/notifier.rb:13:in `order_shipped'
    test/functional/notifier_test.rb:13:in `test_order_shipped'


I have an idea why I'm getting the first error. I've been following the optional exercises at the end of each chapter and I changed the :destroy method in line_items_controller without updating the functional test. Here's the OFFENSIVE code:

def destroy
  @cart = current_cart
  @line_item = @cart.remove_product(@cart.line_items.find(params[:id]))

    respond_to do |format|
      format.html { redirect_to store_url }
      format.js
      format.xml { head :ok }
    end
  end
end


Any idea how to fix this? I'm not super concerned about it, but I'd like to know if I'm on the right track and I think this would be an easy fix. The second error I'm less sure about. I don't get why I'm getting an error for protect_against_forgery? since I'm not calling that method anywhere. Is it a default Rails thing that I'm overlooking?

Anyway, my current strategy has been simply to comment out the tests until later. Which may never come, depending on a variety of factors! I have a sneaking suspicion writing tests will never be one of my strong suits.

Getting back to my original point, it made more sense simply to comment these tests out rather than spend a bunch of time fixing them, especially since my application DOES work. Still, it's a good idea to get a handle on writing tests. I'm doing this for Future Tyler.

Monday, April 25, 2011

That beautiful ArgumentError

Tonight while working on a mailer for the Depot application I'm developing with Agile Web Development with Rails, I screwed my code up and got this error.


I see errors similar to this one pretty often. Most of the time, I've made a typo or forgotten to close a tag or made a call on 'product' instead of '@product'. So I get frustrated when this screen pops up instead of the correct response I was hoping for, but one of the awesome things about Rails is it gives me some guidance on how to fix the error.

In this case, the error claims it's coming from the Orders Controller, but it was really coming from the mailer I created.


What was happening here is these methods aren't referencing anything. So the fix was to write the code like so:


I just skipped over this while working through the book, but if it was MY code, the error information Rails provides would still be valuable. In this case, the error wasn't actually in the Orders Controller, but it still pointed me in the right direction. The screenshot is a bit hard to read at this size (still trying to figure out the best way to display my code) but I'd forgotten to add (order) after defining both order_shipped and order_received.

My hope is I'll see less of these kind of syntax errors as I go along, but I have a feeling typos will be a continual problem.

Monday, April 18, 2011

Headaches and fixing mistakes

You want to talk about Rails headaches? Ok, here we go.

While working on this shopping cart application this evening, I accidentally entered some code into the carts_controller test that was supposed to go into the line_items test. At first I just got frustrated, then tried deleting the cart scaffold and then generating a new cart scaffold. Unfortunately, the carts table already existed, so this didn't work. Then I tried creating a new scaffold called shopping_cart, but I realized that would be too tedious to work with, since every instance in AWD4R will mention cart instead of shopping_cart. Finally I just rolled back the migration, then generated the scaffold again and that worked. Success!

What did I learn from this?
Pay attention.
Keep calm and carry on.
Don't try to hack my way around problems - try solving them correctly.

I'm proud of myself for not quitting when I realized I had a problem and for eventually finding the correct solution. Other than this little hiccup (and it WAS a little hiccup, all things considered) I'm making a ton of progress. What does it say about me that I can't wait to get back to work on Manticore, now that I know how to run rake tests and fix errors that it finds?

One last thing. Speaking as someone with absolutely zero development experience, when I decided to take the advice of my friend Eli (aka jqr) I faced a gigantic learning curve. Here's how I got over my fear of just how much I had to learn: I looked the learning curve right in the eyes and said FUCK YOU. The best way I've found to deal with feeling overwhelmed or in over my head is to find a way to stop being scared of something new and start getting excited about it. Rails is no different.