【问题标题】:Rails: Form input doesn't workRails:表单输入不起作用
【发布时间】:2015-01-18 01:54:25
【问题描述】:

我是 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>

【问题讨论】:

    标签: ruby-on-rails ruby


    【解决方案1】:

    create 操作中的小错误

    改变

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

    @post = Post.new(post_params)
    

    【讨论】:

      猜你喜欢
      • 2018-08-21
      • 2020-07-10
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      • 2016-06-10
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      相关资源
      最近更新 更多