Rails 4.0.4 ActiveModel::ForbiddenAttributesError

Author posted @ 2014年3月23日 18:50 in Ruby , 2211 阅读

Problem:

When I try the rails example project ''rottenpotatoes'' on the SaaS book by Fox and Petterson,  I had problem running the "create" and "update" methods on the webpage. As figure shows, when I click button "Save Changes", it calls the Movie.update function and throws out an error "ActiveModel::ForbiddenAttributesError"

Explanation:

The example code on the text book are 1) http://pastebin.com/g5nq88eJ

# in movies_controller.rb
def create
  @movie = Movie.create!(params[:movie])
  redirect_to movies_path
end

This example works for Rails version < 4. Rails 4.0.4 uses strong parameters[1], so "attr_accessible" and "attr_protected" are out-dated.

Solution: 

def create
    @movie = Movie.new(movie_params)
    if @movie.save
      flash[:notice] = "#{@movie.title} was successfully created."
      redirect_to movies_path
    else
      render 'new' # note, 'new' template can access @movie's field values!
    end
end

private
def movie_params
    params.require(:movie).permit(:title,  :release_date, :rating)
end

see all code: https://github.com/ysonggit/saas-rottenpotatoes

References:

[1] http://edgeapi.rubyonrails.org/classes/ActionController/StrongParameters.html


登录 *


loading captcha image...
(输入验证码)
or Ctrl+Enter