【问题标题】:ForbiddenAttributesError in Rails 5Rails 5中的ForbiddenAttributesError
【发布时间】:2018-03-05 08:30:48
【问题描述】:

即使我在 Rails 中使用了强参数,我也会收到 Forbidden Attributes Error。我有两个模型:帖子和类别。 这是我的帖子控制器: 类 PostsController

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 %>

但我仍然收到错误。

【问题讨论】:

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


    【解决方案1】:

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

    @post = Post.new(allowed_params)

    【讨论】:

    • 谢谢。为我工作
    猜你喜欢
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 2014-04-30
    • 1970-01-01
    • 1970-01-01
    • 2013-12-07
    相关资源
    最近更新 更多