2017-09-24 137 views
1

即使我在Rails中使用了强参数,我仍然收到了禁止属性错误。我有两个模型:帖子和类别。 这里是我的帖子控制器: 类PostsController < ApplicationController的 高清指数 @帖= Post.all 结束ForbiddenAttributesError in Rails 5

def new 
    @post=Post.new 
    @category=Category.all 
end 

def create 
    @post = Post.new(params[:post]) 
    if @post.save 
     redirect_to posts_path,:notice=>"Post saved" 
    else 
     render "new" 
    end 
end 

def allowed_params 
    params.require(:post).permit(:title, :body, :category_id) 
end 

这里是我的帖子查看/新:

<%= form_for @post do |f| %> 
    <p> 
     <%= f.label :title %></br> 
     <%= f.text_field :title%><br/> 
    </p> 
    <p> 
     <%= f.label :body %></br> 
     <%= f.text_area :body%><br/> 
    </p> 
    <p> 
     <%= f.select :category_id, Category.all.collect{|x| [x.name,x.id]},{:include_blank =>"Select one"}%><br/> 
    </p> 
    <p> 
     <%= f.submit "Add Post" %> 
    </p> 
<% end %> 

但我仍然收到错误。

回答

1

您需要使用allowed_params而不是params[:post]

@post = Post.new(allowed_params)

+0

感谢。为我工作 – Rajat

相关问题