Rails has_many:通过验证问题

时间:2015-01-24 18:06:15

标签: ruby-on-rails json validation has-many-through

我一直在使用Rails has_many进行战斗:整整一周。最初我遇到问题collection_select form helper to save

我最终得到了它的工作,并转而试图获得一个json帖子请求,以支持添加一个新的作者。我在使用现在正在运行的表单创建的请求参数之后对json进行了建模。我第一次使用这些参数提出了请求:

{
    "author": {
        "name": "Author Name",
        "post_ids": [
            "1", "2"
        ]
    }
}

我开始测试我的验证,并遇到一个问题,如果发送了一个post_id,数据库中不存在 ,Rails会炸弹@ author.new方法:

请求:

{
    "author": {
        "name": "Author Name",
        "post_ids": [
            "23"
        ]
    }
}

错误:

ActiveRecord::RecordNotFound (Couldn't find Post with 'id'=23):
  app/controllers/authors_controller.rb:32:in `create'

控制器

  def create
    @author = Author.new(author_params)

    respond_to do |format|
      if @author.save
        format.html { redirect_to @author, notice: 'Author was successfully created.' }
        format.json { render :show, status: :created, location: @author }
      else
        format.html { render :new }
        format.json { render json: @author.errors, status: :unprocessable_entity }
      end
    end
  end

这就是轰炸

@author = Author.new(author_params)

我尝试使用验证来确保ID存在,但它在进行验证之前发生了错误。似乎rails正在新方法中创建关联。

我怎样才能抓住这个? 我在Author.new调用之前写了一张支票,以确保发送的author_ids存在,但是如果rails提供了这个能力我希望能够使用内置功能捕获它并将其与其他验证消息一起发回。

型号:

class Author < ActiveRecord::Base
  has_many :post_authors
  has_many :posts, :through => :post_authors
  accepts_nested_attributes_for :post_authors
end

class Post < ActiveRecord::Base
end

class PostAuthor < ActiveRecord::Base
  belongs_to :post
  belongs_to :author
end

模式

ActiveRecord::Schema.define(version: 20150120190715) do

  create_table "authors", force: :cascade do |t|
    t.string   "name"
    t.datetime "created_at", null: false
    t.datetime "updated_at", null: false
  end

  create_table "post_authors", force: :cascade do |t|
    t.integer  "post_id"
    t.integer  "author_id"
    t.datetime "created_at", null: false
    t.datetime "updated_at", null: false
  end

  create_table "posts", force: :cascade do |t|
    t.string   "title"
    t.datetime "created_at", null: false
    t.datetime "updated_at", null: false
  end

end

感谢您的帮助。

验证尝试

我在下面的所有3个模型中都进行了以下验证。我添加了断点和日志消息。在错误发生之前它们都没有被击中,所以在这一点上我甚至无法进行验证,甚至无法进行检查。

class Author < ActiveRecord::Base
  has_many :post_authors
  has_many :posts, :through => :post_authors
  accepts_nested_attributes_for :post_authors

  validate :post_exists

  def post_exists
    Rails.logger.debug("Validate")
  end
end

1 个答案:

答案 0 :(得分:0)

根据rails guide验证仅在调用以下方法时触发:

  • 创建
  • 创建!
  • 保存
  • 保存!
  • 更新
  • 更新<!/ LI>

所以我认为你最好的机会是拯救控制器中的ActiveRecord::RecordNotFound,因为这个问题已经解释了:

how to handle ActiveRecord::RecordNotFound in rails controller?