ZachyBear
ZachyBear

Reputation: 307

Saving to database issue

I am building a database and I am getting an issue with my create action. My code for the create action is:

 def create
        @skills = Skill.new(params[:skill])
      if @skills.save
            redirect_to :action => 'index'
      else
            @skills = Skill.find(:all)
            render :action => 'new'
      end
   end

and my error message is this:

ActiveModel::ForbiddenAttributesError in SkillsController#create
ActiveModel::ForbiddenAttributesError

I assume there is a problem and I am not saving all the needed params but I am not sure. Thanks anyone who knows what might be going wrong and I will keep messing around with it myself. Thanks again.

Upvotes: 0

Views: 42

Answers (1)

acacia
acacia

Reputation: 1387

In your controller add something like this:

private

  def skill_params
    params.require(:skill).permit(:attribute_1, :attribute_2, :attribute_3)
  end

then change create to:

def create
  @skills = Skill.new(skill_params)
  if @skills.save
    redirect_to :action => 'index'
  else
    @skills = Skill.find(:all)
    render :action => 'new'
  end
end

This is specific to Rails 4: this version of ruby on rails fordids direct usage of the params to instanciate a new Model object.

It makes your application more safe by protecting it against some vulnerabilities: for example, imagine if someone requests your application to create a new user and passes admin: true as parameter. The old way may create an admin user. On the contrary, the Rails 4 way force you to filter the parameters.

Upvotes: 3

Related Questions