ruby-on-rails - 两个模型的关联错误。(# 必须存在)
问题描述
我希望能够在创建帖子时选择作者。我有一个帖子和作者模型。在作者的模型中,我规定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)```
解决方案
该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 %>
我们需要更多用于您的后控制器操作和表单视图的代码,以提供更准确的答案。
推荐阅读
- android - Flutter .apk 已构建但未安装在设备/模拟器中
- r - 使用R从文本中提取子字符串
- r - 按匹配项的数量有效地对字符串匹配进行排名
- sql-server - 使用默认(已提交读)隔离模式时如何确保原子规则?
- javascript - Github Pages 在尝试抓取 paper.js 资源时返回 404 错误
- .net - UseStatusCodePagesWithReExecute() 在 .NET Core 3.1 上不起作用
- javascript - 从Angular中的CSV文件读取后如何在UI上填充数据?
- python - 在哪里可以找到照片
- java - 如何检查 SD 卡是格式化为手机存储还是便携式存储?
- java - 在 vertx.executeBlocking 代码中使用 mybatis 代码有什么大问题吗?