首页 > 解决方案 > 两个模型关联错误(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

标签: ruby-on-railsruby

解决方案


构建选择标签时需要传递 id。

尝试:

<%= form.select :author, Author.pluck(:id, :first_name) %>

它创建了一个选择器,其中值是作者id,文本是作者first_name

正如@Chiperific 在评论中所述,您需要更新您的post_params以允许使用 anauthor_id而不是author.


推荐阅读