LearningRoR
LearningRoR

Reputation: 27202

how do i fix undefined method `user_id' for nil:NilClass?

i am trying to start my server after a db:migrate:reset and suddenly my SQlite3 server will not start. I get the error: ActionView::Template::Error (undefined method 'user_id' for nil:NilClass) when the server begins to render my datum/index page. Before i did this i had actual prices in my database so the user_id could be detected and everything worked but now since the prices are gone i believe its giving this error.

Controllers - Datum & Price:

def index
  @prices = Price.all
end

Views - datum/index & prices/index:

<h1>Prices</h1>

<table>
  <tr>
    <th>User</th>
    <th>Date</th>
    <th>Price name</th>
    <th>Price</th>
    <th></th>
    <th></th>
    <th></th>
  </tr>

<% @prices.each do |price| %>
  <tr>
    <td><%= price.user_id %></td>
    <td><%= price.date %></td>
    <td><%= price.price_name %></td>
    <td><%= price.price %></td>
    <td><%= link_to 'Show', price %></td>
    <td><%= link_to 'Edit', edit_price_path(price) %></td>
    <td><%= link_to 'Delete', price, :confirm => 'Are you sure?', :method => :delete %></td>
  </tr>
<% end %>
</table>

<br />

<%= link_to 'New Price', new_price_path %>

I think i am doing this the wrong way as i am new to Rails. My goal was to duplicate my prices/index view so my datum/index is the same so i could then give both unique looks. How do i correct this issue and am i doing this correctly?

Upvotes: 0

Views: 1812

Answers (2)

LearningRoR
LearningRoR

Reputation: 27202

Weird, i think it was giving this error because i was using AptanaStudio 3 with the git terminal. I just restarted everything and it started working now as if the Database needed time to refresh itself. So in conclusion just restart everything and see if it works then.

Upvotes: 0

mu is too short
mu is too short

Reputation: 434665

I'm guessing that you don't know what rake db:migrate:reset does. There's no description string for it so don't ask rake what it does, you have to look at the source:

# desc 'Resets your database using your migrations for the current environment'
task :reset => ['db:drop', 'db:create', 'db:migrate']

So rake db:migrate:reset destroys your database (including any data you had in it), recreates it, and then applies the migrations to bring everything up to date again. But, all your original data is still gone.

The db:drop part of db:migrate:reset probably explains why you're getting nil all over the place. However, you should be getting an empty array from Price.all if all your data was gone so perhaps you've added something after your reset.

Upvotes: 2

Related Questions