user2462645
user2462645

Reputation: 83

Getting started with Rails tutorial 5.7 - Data not showing in view

I am trying out ruby on rails, going through the "Getting started with Ruby" tutorial. I have gone through steps to and including 5.7 and by now I should be able to create a new post and view it, the post is created, but the title and text is not showing.

1

The controller: posts_controller.rb

class PostsController < ApplicationController
def new
end

def create
  @post = Post.new(params[post_params])
  @post.save
  redirect_to @post
end
def show
    @post = Post.find(params[:id])
end
private
    def post_params
        params.require(:post).permit(:title, :text)
    end
end

The view to create the post

<h1>New Post</h1>

<%= form_for :post, url: posts_path do |f| %>
  <p>
    <%= f.label :title %><br>
    <%= f.text_field :title %>
  </p>
 
  <p>
    <%= f.label :text %><br>
    <%= f.text_area :text %>
  </p>
 
  <p>
    <%= f.submit %>
  </p>
<% end %>

The show view for showing the post.

<p>
  <strong>Title:</strong>
  <%= @post.title %>
</p>

<p>
  <strong>Text:</strong>
  <%= @post.text %>
</p>

My guess is that the issue is with the passing of data to the database, but i can't figure out whats wrong. Any idea?

Upvotes: 0

Views: 159

Answers (3)

user2462645
user2462645

Reputation: 83

I figured out that this line was the issue

@post = Post.new(params[post_params])

It should be

@post = Post.new(post_params)

Thanks to everybody who answered!

Upvotes: 1

zeantsoi
zeantsoi

Reputation: 26203

In the new controller action, be sure to assign a new instance of Post to an instance variable:

# app/controllers/posts_controller.rb
def new
  @post = Post.new
end

Then, pass the @post instance variable to the form_for helper in the view:

# app/views/posts/new.html.erb
<%= form_for @post do |f| %>

The form_for helper expects a resource to be passed to it; the form is automatically submitted to the correct route based on the type of resource passed. You're passing a new resource in this instance, so the form is routed to the resource's create action.

Upvotes: 1

kacy hulme
kacy hulme

Reputation: 141

you may want to change the title of this post to something like "data not showing in view". here is what i would make sure of: that you have in fact created items in your database, i assume you are using sqlite. you can do this in the rails console. or you can enter directly into the form or "The view to create the post" as you call it. it seems to me that your show action in your controller and your view are correct -- at least, they should show your data. even without the form working, your data should still show up -- if you input your data via rails console.

Upvotes: 0

Related Questions