0

由于 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

怎么了?我真的一点头绪都没有!

4

0 回答 0