# article.rb
class Article < ActiveRecord::Base
has_many :article_categories, dependent: :destroy
has_many :categories, through: :article_categories
validates :title, :description, :body, presence: true
validates :categories, presence: true
validates_associated :categories
end
#articles_controller.rb
def create
@article = Article.new(params[:article])
respond_to do |format|
if @article.save
format.html { redirect_to @article, notice: 'Article was successfully created.' }
format.json { render json: @article, status: :created, location: @article }
else
format.html { render action: "new" }
format.json { render json: @article.errors, status: :unprocessable_entity }
end
end
end
我有与一个或多个类别相关的文章模型。每次保存记录时,我都要确保将文章分配给某个类别。在更新,这工作得很好,但在创造,我得到一个unprocessable entity
因为ArticleCategory
协会无法创建,因为它需要的物品的id
。但是,该id
没有设置直到Article
被保存。但我无法保存无效的模型。你明白了。我如何在不牺牲我的验证的情况下使用create
对象?Rails 3.1:使用has_many保存新对象时验证失败:通过关联
编辑:我固定验证线。这是清理,除去一些其他的东西,所以我不小心删除了presence: true
我很惊讶,你是不是在这里得到一个'ArgumentError'。你需要在'validates:categories'中指定一个验证,你的第一个'validates'行也会关闭。 – 2012-01-03 15:28:15