ruby-on-rails - 两个模型关联错误(AssociationTypeMismatch)
问题描述
我希望能够在创建帖子时选择作者。我有一个帖子和作者模型。在作者的模型中,我规定has_many :posts
了 ,而在 Post 模型belongs_to :author
中。在表单视图中,创建了一个作者列表<%= form.select(:author, Author.all.collect {|p| [ p.first_name] }) %>
在我规定的后控制器中:
def post_params
params.require(:post).permit(:title, :content, :picture, :author)
end
但是,在创建帖子时出现错误ActiveRecord::AssociationTypeMismatch in PostsController#create
Author(#70151313190260) expected, got "AuthorName" which is an instance of String(#47111701634520)
UPD。我得到的一切:
Started POST "/posts" for ::1 at 2019-11-17 22:39:33 +0200
Processing by PostsController#create as HTML
Parameters: {"authenticity_token"=>"o8rcT1Jo/seI+zs+CRa6Ro3Wu14oz7OJ9zE0OLgtjkWVAOVJ05VeRM17Je27STO0/pV9Sdrn5XinOANv6VCwlA==", "post"=>{"author"=>"4", "title"=>"TitleName", "content"=>"SomeContent"}, "commit"=>"Submit"}
Completed 500 Internal Server Error in 2ms (ActiveRecord: 0.0ms | Allocations: 842)
ActiveRecord::AssociationTypeMismatch (Author(#69935628031800) expected, got "4" which is an instance of String(#47189092695520)):
app/controllers/posts_controller.rb:27:in `create'
在 post_controller 中创建定义:
def create
@post = Post.new(post_params)
respond_to do |format|
if @post.save
format.html { redirect_to @post, notice: 'Post was successfully created.' }
format.json { render :show, status: :created, location: @post }
else
format.html { render :new }
format.json { render json: @post.errors, status: :unprocessable_entity }
end
end
end
#before action
def set_post
@post = Post.find(params[:id])
end
解决方案
构建选择标签时需要传递 id。
尝试:
<%= form.select :author, Author.pluck(:id, :first_name) %>
它创建了一个选择器,其中值是作者id
,文本是作者first_name
。
正如@Chiperific 在评论中所述,您需要更新您的post_params
以允许使用 anauthor_id
而不是author
.
推荐阅读
- json - laravel guzzle 读取数据库而不是 json
- c# - C# Entity Framework .Any() 无法创建“匿名类型”类型的常量值
- java - 如何通过命令行选项使用 Maven Surefire 排除标签?
- sql - 如何在 PostgreSQL 上将所有列转换为正确的大小写/标题大小写?
- laravel - 是否应该在数据库中表示所有模型,或者如果模型没有在数据库中表示,则最好只制作一个控制器?
- angular - Angular 中的单元测试、集成测试和端到端测试有什么区别?
- bash - 更改 txt 文件中的天数
- python - 从 Google Colaboratory 连接到 Mongodb Atlas 时出错
- java - TestNG Selenium WebElement 找不到
- http - XMLHTTP 或 ServerXMLHTTP 在没有 http 的情况下工作?