首页 > 解决方案 > 两个模型的关联错误。(# 必须存在)

问题描述

我希望能够在创建帖子时选择作者。我有一个帖子和作者模型。在作者的模型中,我规定has_many :posts了 ,而在 Post 模型belongs_to :author中。在表单视图中,创建了作者列表<%= form.collection_select(:author_id, Author.all, :id, :last_name, class:'form-control' ) %>。在我规定的后控制器中:

    def post_params
       params.require(:post).permit(:name, :title, :content, :picture, :author_id)
    end

架构.rb:

  create_table "posts", force: :cascade do |t|
    t.string "name"
    t.string "title"
    t.text "content"
    t.datetime "created_at", precision: 6, null: false
    t.datetime "updated_at", precision: 6, null: false
    t.integer "author_id"
    t.index ["author_id"], name: "index_posts_on_author_id"
  end

但是在创建帖子时,我收到一个错误: Author must exist

日志:

Started POST "/posts" for ::1 at 2019-11-18 00:51:40 +0200
Processing by PostsController#create as HTML
  Parameters: {"authenticity_token"=>"68iOabMzXQPuvC83f5Oe3kQEl5rFeQLQNCuMjvtRZgfdArdvMs79gKs8MeTNzBcsN0dRjTdRVCFkIrvZqixY1g==", "post"=>{"author_id"=>"2", "name"=>"SomeName", "title"=>"SomeTitle", "content"=>"SomeContent"}, "commit"=>"Submit"}
  Rendering posts/new.html.erb within layouts/application
  [1m[36mAuthor Load (0.2ms)[0m  [1m[34mSELECT "authors".* FROM "authors"[0m
  ↳ app/views/posts/_form.html.erb:16
  Rendered posts/_form.html.erb (Duration: 8.2ms | Allocations: 2071)
  Rendered posts/new.html.erb within layouts/application (Duration: 9.1ms | Allocations: 2157)
Completed 200 OK in 34ms (Views: 30.4ms | ActiveRecord: 0.2ms | Allocations: 13745)```

标签: ruby-on-railsruby

解决方案


Author must exist错误表明您的新帖子未通过验证:存在将author_id帖子链接到作者的属性值。默认情况下,此验证与关联辅助方法捆绑在一起belongs_to(并且可以根据上面 Simon Franzen 的评论禁用:belongs_to: model, optional: true.

由于您允许author_id键入post_params,因此链中的薄弱环节要么是您的post#create控制器操作,要么是您的_form.html.erb视图。对post#create, 和的一些建议_form.html.erb

def create
  post = Post.create(post_params)
  redirect_to post
end
<%= form_with model: @post do |form| %>
  ...
  <%= form.label :author %>
  <%= form.collection_select :author_id, Author.all, :id, :name %>
  ...
  <%= form.submit "Create Post" %>
<% end %>

我们需要更多用于您的后控制器操作和表单视图的代码,以提供更准确的答案。


推荐阅读