user3277295
user3277295

Reputation: 51

Strong parameters in Ruby

I'm getting the error message about strong parameters. I think it's just that rails 4 doesn't use attributes anymore. the code for my toy.rb is:

class Toy < ActiveRecord::Base 
  attr_accessible :name, :price, :vendor 
  validates :name, :presence => true 
  validates :price, :presence => true 
  validates :price, :numericality => true 
  validates :vendor, :presence => true 
end 

how can I change this to strong parameters?

EDIT: I used a different rb i changed it to employees and this is what I have:

  class Employee < ActiveRecord::Base
params.require(:employee).permit(:first, :last, :salary, :salary, :ssn)
validates  :first, :presence => true
validates  :last, :presence => true
validates  :salary, :presence => true
validates  :salary, :numericality => true
validates  :ssn, :presence => true 

end

It's still telling me "ndefined local variable or method `params' for #"

Upvotes: 2

Views: 632

Answers (2)

Richard Peck
Richard Peck

Reputation: 76774

Strong params are designed to help your controller send specific data to your model. It's meant to protect your app against unauthorized data being passed:

#app/controllers/toys_controller.rb
Class ToysController < ActiveRecord::Base
    def new
        @toy = Toy.new #-> creates a blank AR object
    end

    def create
        @toy = Toy.new(toys_params) #->creates new AR object (populating with strong params)
        @toy.save
    end 

    private
    def toys_params
        params.require(:toys).permit(:your, :params, :here)
    end 
end 

Upvotes: 0

Eric Andres
Eric Andres

Reputation: 3417

The code you need is

params.require(:toy).permit(:name, :price, :vendor)

You will put this in your controller. Typically, you create a private method:

def create
  Toy.create(toy_params)
end

private
def toy_params
  params.require(:toy).permit(:name, :price, :vendor)
end

See http://guides.rubyonrails.org/getting_started.html#saving-data-in-the-controller for more information.

Edit I think I might have misled you with my original answer. The code goes in the controller, not the model.

Upvotes: 2

Related Questions