2014-02-05 37 views
2

我收到有關強參數的錯誤消息。我認爲這只是導軌4不再使用屬性。我toy.rb的代碼是:Ruby中的強參數

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 

我該如何將此更改爲強參數?

編輯:我使用了不同的RB我改成了員工,這是我所:

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 

它仍然告訴我,「ndefined局部變量或方法`PARAMS'爲# 「

+4

您是否試過使用谷歌搜索「導軌4強參數」? –

回答

2

你需要的代碼是

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

你會把這個在您的CONTRO米勒。通常,您創建一個私有方法:

def create 
    Toy.create(toy_params) 
end 

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

有關更多信息,請參閱http://guides.rubyonrails.org/getting_started.html#saving-data-in-the-controller

編輯 我想我可能誤導了你我的原始答案。代碼放在控制器中,而不是模型。

+0

我在哪裏可以放置該代碼?對不起,我很新 – user3277295

+0

只是增加了一點。請遵循鏈接,因爲我無法在此答案中提供詳盡的示例。 –

+1

標準的Rails教程也涵蓋了這個主題:http://guides.rubyonrails.org/getting_started.html#saving-data-in-the-controller – fivedigit

0

強PARAMS旨在幫助您控制器特定數據發送到你的模型。它旨在保護您的應用程序免受未經授權的數據通過:

#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