我是rails的新手,所以我一直在练习基本的CRUD应用程序。一切似乎都有效,除了我提交新的表单条目时它不会保存任何数据。我现在已经设置了一些验证,所以它现在甚至无法提交。然而,我仍然可以编辑其他条目以添加新数据。所以我的编辑工作正常。
这是我的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>
答案 0 :(得分:1)
create
行动中的小错误
从
改变@post = Post.new(post_params[:post])
到
@post = Post.new(post_params)