0

I have the following view in app/views/posts/index.html.erb:

<% @posts.each do |post| %>

<%= post.user %> is listening to <%= post.song %> by <%= post.artist %> from <%= post.album %>

<% end %>

And the corresponding controller:

class PostsController < ApplicationController
  def index
    @posts = Post.find(:all)   
  end

  def show
    @post = Post.find(params[:id])  
  end 

  def new
    @post = Post.new           
  end

  def create                   
    @post = Post.new(params[:posts])
    if @post.save              
      redirect_to action: "index"     
    else                       
      @posts = Post.find(:all) 
      render action: 'new'     
    end
  end
end

The problem is, when I create a record with the song attribute being "The Sound of Settling", the artist attribute being "Death Cab for Cutie", and the album atrribute being "Transatlanticism", nothing shows up when I render the index view.

6
  • Are you sure the post is being created successfully? Can you post the snippet from your development.log file showing the output when you are creating the Post? Commented Dec 25, 2012 at 15:19
  • 3
    Your index code looks like it can't go wrong. I'd suspect that your form is off somehow. (Hey, how come you're using params[:posts] in your create action?) Commented Dec 25, 2012 at 15:21
  • @cbascom (0.1ms) begin transaction SQL (144.9ms) INSERT INTO "posts" ("album", "artist", "created_at", "song", "updated_at") VALUES (?, ?, ?, ?, ?) [["album", nil], ["artist", nil], ["created_at", Tue, 25 Dec 2012 15:28:49 UTC +00:00], ["song", nil], ["updated_at", Tue, 25 Dec 2012 15:28:49 UTC +00:00] Commented Dec 25, 2012 at 15:34
  • 2
    Notice all values are nil? As bdares said :posts is incorrect, should be :post in the create action Commented Dec 25, 2012 at 15:43
  • Thanks, that worked. I'm such an idiot sometimes. Commented Dec 25, 2012 at 15:45

2 Answers 2

1

As @house9 and @bdares said, I had :posts in my create action when it should have been :post.

Sign up to request clarification or add additional context in comments.

Comments

1

For situations like this, the command line is invaluable.

$ rails console

Then play around, insert some data, fetch some. Start off with what goes wrong here:

> @posts = Post.find(:all)
> pp @posts

No results? there are no Posts, at all. Probably because of a problem on insertation:

> @post = Post.new({:user => 1, :song => "give it up", :artist => "rick", :album => "youtube greatest hits"})
> @post.valid?
> pp @post.errors
> @post.save!

It allows you to eliminate most problems beforehand.

Comments

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.