我创建了一个rake populate文件来构建虚拟数据。
@corp_page = CorporatePage.create(title: 'Home', static_descriptor: 'Home')
@panel_count = CorporatePanel::PANEL_TYPE.count
if @corp_page.title == 'Home'
----
else
puts "Corp Page not saved"
puts @corp_page.inspect
end
在检查时,我的验证似乎阻止了实例的制作。为什么呢?
Freddys-MacBook-Pro:gll_corporate McGroarty$ rake db:populate
not saved
#<ActiveModel::Errors:0x007fdb2f5162f8 @base=#<CorporatePage id: nil, title: nil, static_descriptor: nil, workflow_state: "draft", created_at: nil, updated_at: nil>, @messages={:title=>["can't be blank"]}>
这些值完全符合验证。为什么这不起作用?
# == Schema Information
#
# Table name: corporate_pages
#
# id :integer not null, primary key
# title :string(255)
# static_descriptor :string(255)
# workflow_state :string(255) default("draft")
# created_at :datetime
# updated_at :datetime
#
class CorporatePage < ActiveRecord::Base
HOME_PAGE='Home'
PAGE_TYPES=[HOME_PAGE]
has_many :corporate_panels
validates_presence_of :title
validates :static_descriptor, inclusion: PAGE_TYPES
由于
答案 0 :(得分:1)
Rails默认阻止对变量进行质量分配
对于rails 4,据我所知,您可以将此行添加到应用程序的Gemfile中:
gem 'protected_attributes'
执行
bundle install
从命令行
并在您的模型中添加
attr_accessible :title, :static_descriptor
通过这种方式,您可以将允许批量分配的属性列入白名单。 实际上它曾经是一个默认功能,但已被弃用,我仍然在学习新的'正确方法':)
我会评论,因为我的答案肯定会遗漏很多,但我仍然不被允许。 (50条评论的声誉)