我已经创建了一个rake填充文件来构建虚拟数据。
@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"]}>
值与验证的值完全一致。为什么这不起作用?
<标题> CorpPage模型# == 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
Rails 4 谢谢
标题>Rails默认防止大量变量赋值
对于rails 4,据我所知,您可以将这一行添加到应用程序的Gemfile中:
gem 'protected_attributes'
执行bundle install
命令行并在模型中放入
attr_accessible :title, :static_descriptor
这样,您将允许大量分配的属性列入白名单。实际上,它曾经是一个默认功能,但已被弃用,我仍在学习新的"正确的方式":)
我本来会评论的,因为我的答案肯定遗漏了很多,但我仍然不被允许。(50好评评论)