Rails 4强参数阻止了储蓄

时间:2013-10-30 15:21:56

标签: console ruby-on-rails-4 strong-parameters

由于Rails 4强大的参数,我只是把头撞在墙上。

基本上,我有一个非常简单的模型:

class Band < ActiveRecord::Base
  validates_presence_of :name
  has_many :users
  has_many :donations
  attr_accessible :name #I'm using protected_attributes
end

用户必须登录才能创建乐队,当创建乐队时,这里是我的控制器

def new
  @band = Band.new
end

def create
 @band = Band.new(band_params)

 respond_to do |format|
  if @band.save

    format.html { redirect_to @band, notice: 'La band è stata creata' }
    format.json { render action: 'show', status: :created, location: @band }
  else
    format.html { render action: 'new' }
    format.json { render json: @band.errors, status: :unprocessable_entity }
  end
 end
end

private

def set_band
  @band = Band.find(params[:id])
end

def band_params
   params.require(:band).permit(:name)
end

使用此配置,无法创建新的Band对象,甚至无法从控制台创建!

b = Band.new
b.save
=> false
b.errors.messages
=> {:name=>["can't be blank"]}
b.band = "band's name"
b.save
=> false
b.errors.messages
=> {}
Band.create!(name: "OneName")
WARNING: Can't mass-assign protected attributes for Band: name
ActiveRecord::RecordInvalid: Validation failed: Name can't be blank

发生了什么事? 我真的不知道!

0 个答案:

没有答案