0

I'm new to rails so I've been practicing with a basic CRUD application. Everything seems to work except for when I submit a new form entry it doesn't save any of the data. I've now set up some validations so it won't even submit now. Yet I can still edit other entries to add new data. So my edit is working.

Here's my posts_controller.rb

class PostsController < ApplicationController
    def index
        @posts = Post.all
    end

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

    def new
        @post = Post.new
    end

    def create
        @post = Post.new(post_params[:post])
        if @post.save
            redirect_to posts_path, :notice => "Your email was sent!"
        else 
            render "new"
        end
    end

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

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

        if @post.update_attributes(post_params)
            redirect_to posts_path, :notice => "Your email has been updated."
        else
            render "edit"
        end 
    end

    def destroy
        @post = Post.find(params[:id])
        @post.destroy
        redirect_to posts_path, :notice => "Your email has been deleted"
    end

private
    def post_params
    params.require(:post).permit(:name, :email, :message)
    end
end

_form.html.erb

<%= form_for @post do |f| %>
  <% if @post.errors.any? %>
    <h2>Errors:</h2>
    <ul>
      <% @post.errors.full_messages.each do |message| %>
      <li><%= message %></li>
      <% end %>
    </ul>
  <% end %>

  <%= f.label :name %>
  <%= f.text_field :name %>
  <br>
  <br>

  <%= f.label :email %>
  <%= f.text_field :email %>
  <br>
  <br>

  <%= f.label :message %><br>
  <%= f.text_area :message %>
  <br> 

  <%= f.submit "Send Email" %>
<% end %>

edit.html.erb

<h1>Edit</h1>

<%= render "form" %>

index.html.erb

<h1>Emails</h1>
<hr>

<% @posts.each do |post| %>
    <p><em>Name:</em> <%= link_to post.name, post %></p>
    <p><em>Email:</em> <%= post.email %></p>
    <p><em>Message:</em> <%= post.message %></p>
    <p><%= link_to "Edit", edit_post_path(post) %>
    | <%= link_to "Delete", post, :method => :delete %>
    </p>
    <hr>
<% end %>

<p><%= link_to "Add a New Post", new_post_path %></p>

new.html.erb

<h1>Email</h1>
<p>Send an email:</p>

<%= render "form" %>

show.html.erb

<p><em>Name:</em> <%= @post.name %></p>
<p><em>Email:</em> <%= @post.email %></p>
<p><em>Message:</em> <%= @post.message %></p>
<hr>

1 Answer 1

1

Small mistake in your create action

change from

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

to

@post = Post.new(post_params)
Sign up to request clarification or add additional context in comments.

Comments

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.