Veske
Veske

Reputation: 557

Trying to get User posts to work

So I am following Hartl tutorial mostly right now but I wanted to make it so that a user can just make a post, that post will then belong to him and show it in a simple way on a seperate page for instance. No twitter like stuff.

def create
      @post = current_user.posts.build(post_params)
    if @post.save
      flash[:success] = "Post created!"
      redirect_to root_url
    else
      render 'posts/index'
    end
  end

Now I have this in my post_controller. I have form that posts to @post when submitted. But I dont get the flash message which means the post was not saved even when I pressed submit. Why is that first of all and secondly, I dont really get the code line too : @post = current_user.posts.build(post_params). What is that build supposed to do exactly? Am I not supposed to just do a Post.new(post_params)? And modify it a bit so that the post would also belong to a user?

I made a gist of my user and post model: https://gist.github.com/Veske/7988593

Server log:

Started POST "/posts/index" for 127.0.0.1 at 2013-12-16 17:19:52 +0200
Processing by PostsController#index as HTML
  Parameters: {"utf8"=>"✓", "authenticity_token"=>"iT08NreZv83WtImK6V9/jXZOpgtzwSLjlxB7T/wn0E4=", "text"=>"This is a s
 post!", "commit"=>"Submit!"}
  Rendered posts/index.html.erb within layouts/application (1.0ms)
  User Load (1.0ms)  SELECT "users".* FROM "users" WHERE "users"."remember_token" = '390d667f7603eee5976fd8500a9a8776c
d3' LIMIT 1
  Rendered layouts/_menu.html.erb (4.0ms)
  Rendered layouts/_footer.html.erb (0.0ms)
Completed 200 OK in 21ms (Views: 19.0ms | ActiveRecord: 1.0ms)

This is my form

<%= form_tag(@post) do %>
    <div class="forms">
    <%= text_area_tag(:content, nil, placeholder: "Type text in here...")%>
    <%= submit_tag 'Submit!' %>
    </div>
<% end %>

Upvotes: 1

Views: 68

Answers (2)

Justin
Justin

Reputation: 4940

Here is your answer. I made a gist https://gist.github.com/licatajustin/7989891

For next time, you can easily check by testing through your Command Line.

In your console, type in

rails c

> u = User.first
> u.posts.create(content: "My first post")

and see if that works

Upvotes: 2

Yule
Yule

Reputation: 9764

You're sending text = "This is a s post!" But your model suggests that the attribute 'content' is required (not 'text')

Therefore @post.save is failing and you're falling into the failed statement. I'd suggest you need to look at the form that creates this post as it doesn't seem to be creating the correct attributes.

Upvotes: 1

Related Questions