我已经开始学习 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/