6

無知で申し訳ありませんが、私は Ruby だけでなく、プログラミング全般についてまったくの初心者です。rubyonrails.org のエッジ ガイドの例に取り組んでいます。次のエラーが表示され、アプリが最後に機能してから入力したすべてのコードを確認したにもかかわらず、修正できません。

PostsController#create の NoMethodError

{"title"=>"", "text"=>""}:ActiveSupport::HashWithIndifferentAccess の未定義のメソッド「permit」

そして、これは私の posts_controller.rb がどのように見えるかです:

class PostsController < ApplicationController
  def new
    @post = Post.new
  end

  def create
    @post = Post.new(params[:post].permit(:title, :text))

    if @post.save
      redirect_to action: :show, id: @post.id
    else
      render 'new'
    end    
  end

  def show
    @post = Post.find{params[:id]}
  end  

  def index
    @posts = Post.all
  end        
end

私は何を間違っていますか?

助けてくれてありがとう!

4

4 に答える 4

8

この行の代わりに:

@post = Post.new(params[:post].permit(:title, :text))

これを試して

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

strong_parametersに出くわし、いくつかのチュートリアルの取り違えがあったようです。

を使用したい場合はstrong_parameters、gemfile に gem を追加し、次のように初期化子を作成します。

ActiveRecord::Base.send(:include, ActiveModel::ForbiddenAttributesProtection)

その後、コントローラーは次のようになります。

class PostsController < ApplicationController
  def new
    @post = Post.new
  end

  def create
    @post = Post.new(post_params)

    if @post.save
      redirect_to action: :show, id: @post.id
    else
      render 'new'
    end    
  end

  def show
    @post = Post.find_by_id(params[:id].to_i)
  end  

  def index
    @posts = Post.all
  end    

  private

  def post_params
    params.require(:post).permit(:title, :text)
  end    
end
于 2013-04-19T16:26:08.323 に答える