2012-01-03 42 views
1
# 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

+0

我很惊讶,你是不是在这里得到一个'ArgumentError'。你需要在'validates:categories'中指定一个验证,你的第一个'validates'行也会关闭。 – 2012-01-03 15:28:15

回答

-2

看一看Rails的指南为这里的正确格式:

has_many :patients, :through => :appointments 

From here!我想你会以不正确的格式找到你的声明。

+0

他使用Ruby 1.9风格的哈希,语法看起来很好。 – 2012-01-03 15:35:34

0

而是验证该文章有很多类别,你可以尝试验证连接表的存在,如:

# article.rb 
validates :article_categories, presence: true 
+0

但是,ArticleCategory不能保存没有的article_id指向的东西。那就是问题所在。在创建时,“id”不存在。在更新时(我在'rails console'手动创建的现有文章中)很好用。 – jxpx777 2012-01-03 15:37:57

+0

哦不对,是去掉验证了的article_id,并确保为article_id的设置在DB列空约束,你没有得到一个NULL值。 – 2012-01-03 15:39:39

+0

您在文章分类模型上验证“article_id”或“article”吗?如果您验证关联“article”而不是'article_id'列,它可能会传递验证。 – 2012-01-03 15:42:28

相关问题