ruby-on-rails - PostsController 中的 ActiveModel::ForbiddenAttributesError#create

标签 ruby-on-rails ruby ruby-on-rails-4

我已经开始学习 Ruby on Rails。

我遇到以下错误:ActiveModel::ForbiddenAttributesError in PostsController#create

代码如下:

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.create(params[:post]) // Its showing me error here

    if @post.save
      redirect_to posts_path notice: "Your Post was saved"
    else
      render "new"
    end
  end

end

new.html.erb

<h1> Add a New Post </h1>

<%= form_for @post do |f| %>
  <p>
    <%= f.label :title %><b/>
    <%= f.text_field :title %><b/>
  </p>
  <p>
    <%= f.label :content %><b/>
    <%= f.text_area :content %><b/>
  </p>
    <%= f.submit "Add a New Post" %>
<%  end %>

post.rb

class Post < ActiveRecord::Base
  validates_presence_of :title, :content
end

请告诉我哪里出了问题。顺便说一句,我正在使用 Rails4

最佳答案

在 rails4 中有强大的参数,所以你不能这样做:

@post =  Post.create(params[:post])

你需要

@post =  Post.create(post_params)

post_params 是 Controller 中的一个方法:

private

def post_params
  params.require(:post).permit!
end

permit! 将允许任何事情。您可以将它限制为您想要允许的内容,例如 params.require(:post).permit(:title, :content)

关于ruby-on-rails - PostsController 中的 ActiveModel::ForbiddenAttributesError#create,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/28606398/

相关文章:

ruby-on-rails - 带有 Rails 应用程序的 JMeter 真实性 token

ruby-on-rails - Rails 创建连接表如何验证对的唯一性

ruby - 在发布 gem 之前编译 Assets

mysql - 初学者 Ruby/MSQL 错误

ruby-on-rails - 如何在 Rails 共享主机上执行 restart.txt ruby

ruby - Kaminari 和 Capybara 冲突

ruby - Rails4 如何使用 sferik/twitter gem 发布来自网站的图片?

ruby-on-rails - 如何在 Rails 4.0 中仅继承 ActiveRecord 模型的连接

javascript - 如何使用 Dropzone.js 和 Rails 4 重定向提交页面?

html - 未定义的方法 `error_span' - Rails 项目