我正在使用 Ruby on Rails v3.2.2。我想解决使用时与外键验证相关的问题accepts_nested_attributes_for
and validates_associated
回报率方法。也就是说,我有以下模型类:
class Article < ActiveRecord::Base
has_many :category_associations, :foreign_key => 'category_id'
accepts_nested_attributes_for :category_associations, :reject_if => lambda { |attributes| attributes[:category_id].blank? }
validates_associated :category_associations
end
class CategoryAssociation < ActiveRecord::Base
belongs_to :article, :foreign_key => 'article_id'
belongs_to :category, :foreign_key => 'category_id'
validates :article_id, :presence => true
validates :category_id, :presence => true
end
...我有以下控制器操作:
class ArticlesController < ApplicationController
def new
@article = Article.new
5.times { @article.category_associations.build }
# ...
end
def create
@article = Article.new(params[:article])
if @article.save
# ...
else
# ...
end
end
end
通过上面的代码(“灵感”来自嵌套模型表格第 1 部分 http://railscasts.com/episodes/196-nested-model-form-part-1?view=asciicast铁轨铸造)我的目的是在创建文章时存储类别关联 (note:类别对象已存在于数据库中;就我而言,我只想存储创建类别关联)。但是,当我从相关视图文件提交相关表单时,出现以下错误(我正在记录错误消息):
{:"category_associations.article_id"=>["can't be blank"], :category_associations=>["is invalid"]}
为什么会发生这样的事validates_associated
seems https://stackoverflow.com/questions/5176510/validates-associated-not-checking-existence-of-associations#comment5826558_5176607运行该方法article.category_association.valid?
但前提是article.category_association.article_id
is not nil
?如何解决存在验证的问题article_id
外键?
但是,如果我注释掉validates :article_id, :presence => true
in the CategoryAssociation
模型类,它按预期工作,但是好像是not正确的做法not验证外键 https://stackoverflow.com/questions/13345250/is-it-really-needed-to-validate-foreign-keys/13346791#13346791.
如果我注释掉validates_associated :category_associations
in the Article
模型类,我仍然收到错误:
{:"category_associations.article_id"=>["can't be blank"]}